Search code examples
arraysmatlabcell

How to use cell arrays in Matlab?


I am a beginner at using Matlab and came across cell arrays but I am not sure how to use indexing for it.

I have created a cell array of 5 rows and 3 cols by doing the following:

A = cell(5,3);

Now is it possible to go through the cell array by row first and then col like how a nested for loop for a normal array?

    for i=1:5
        for j=1:3
           A{i,j} = {"random"} //random numbers/ string etc
        end
    end

Solution

  • With cell arrays you have two methods of indexing namely parenthesis (i.e. (...)) and braces (i.e. {...}).

    Lets create a cell array to use for examples:

    A = {3,   9,     'a'; 
         'B', [2,4], 0};
    

    Indexing using paranthesis returns a portion of the cell array AS A CELL ARRAY. For example

    A(:,3)
    

    returns a 2-by-1 cell array

    ans =
    
        'a'
         0
    

    Indexing using braces return the CONTENTS of that cell, for example

    A{1,3}
    

    returns a single character

    ans =
    
    a
    

    You can use parenthesis to return a single cell as well but it will still be a cell. You can also use braces to return multiple cells but these return as comma separated lists, which is a bit more advanced.

    When assigning to a cell, very similar concepts apply. If you're assigning using parenthesis, then you must assign a cell matrix of the appropriate size:

    A(:,1) = {1,1}
    

    if you assign a single value using parenthesis, then you must put it in a cell (i.e. A(1) = 2 will give you an error, so you must do A(1) = {2}). So it's better to use braces as then you are directly affecting the contents of the cell. So it is correct to go

    A{1} = 2
    

    this is equivalent to A(1) = {2}. Note that A{1} = {2}, which is what you've done, will not give a error but what is does is nests a cell within your cell which is unlikely what you were after.

    Lastly, if you have an matrix inside one of your cells, then Matlab allows you to index directly into that matrix like so:

    A{2,2}(1)
    
    ans = 
    
         3