arraysmatlabcell-array

MATLAB Using colon operator with cell assignment


I had the following line of code to set the first column of a cell array to false so it could be used for checkboxes in a uitable:

result{:,1} = false;

It ran as expected many times, but seemingly randomly threw up this error:

The right hand side of this assignment has too few values
to satisfy the left hand side.

I ended up changing the line to:

result(:,1) = {false};

and it seems to be working as before.

Is there any reason why the first way shouldn't work? Or any reason why it would work for a while and then stop?


Solution

  • You original line

    result{:,1} = false;
    

    will work if result has one row, but not if it has several rows. So my guess is that it worked initially because result had one row, but stopped working because result acquired new rows.

    Why is this so?

    If result has a single row, the statement result{:,1} = false; is the same as result{1,1} = false;, that is, "set the content of the upper left cell of result to false", which is fine. However, if result has n rows, the left-hand side of the statement result{:,1} = false; is a comma-separated list of the contents of n cells. You can't assign a single value to several cells' contents. Matlab does not automatically replicate that value and put it as all those cells' contents.

    A solution is to tell Matlab to do that replication using deal (which effectively "deals" that value to all left-hand side "receivers"):

    result{:,1} = deal(false);
    

    Of course, this also works if there is a single row.

    Another possibility would be to use, as you did,

    result(:,1) = {false};
    

    This means "make all cells in the first column of result equal to a cell containing false". Note the difference with the previous case: now we are assigning a cell to several cells. Matlab is happy with that, and automatically replicates the right-hand cell. And again, this also works for a single row as a particular case.