Search code examples
matlabsyntaxcommentsconcatenationcell-array

Cell array concatenation error in Matlab when certain lines are commented


I'm trying to create a cell array of cell arrays in Matlab. The code that I currently have works exactly like I need it to. The problem is basically that if I comment out any line that isn't the first, middle, or last I get the error:

Error using ==> vertcat CAT arguments dimensions are not consistent.

I've been researching this for awhile, and I found one other person with the exact same problem...

http://www.programmersheaven.com/mb/ctocplusplustomatlab/424275/424275/mysterious-reason-for-cat-error-when-defining-cell-array/

...however, there is no solution to this post.

Here's my code (the 4s stand for possible integer values the variables hold):

cell = {{4} ...
    {4} ...
    {4} ...
    {4} ...
    {} ...
    {4} ...
    {4} ...
    {4} ...
    {4} ...
    {4 4 4 4} ...
    {4} ...
    {4} ...
    {4} ...
    {4} ...
    {4} ...
    {4 4 4 4} ...
    {5} ...
    {} ...
    {4} ...
    {4} ...
    {} ...
    {} ...
    {} ...
    {} ...
    {} ...
    {} ...
    {} ...
    {} ...
    {} ...
    };

(I can't get it to look exactly the same here... after every ellipse the code moves to a new line in my version)

Let's say I comment out the line with the 5 in it. It will always return the concatenation error. Any idea why this is happening?

Thanks in advance,

Nicole


Solution

  • Here's a smaller example:

    c = {...
        {1}... % you can comment out this line
        {2}... % error when commenting this line
        {3}... % you can comment this line (will make a 2-by-2 array)
        {4}... % error when commenting this line
        {5}... % you can comment out this line
        }
    

    The commented line will be considered an empty line by Matlab. When catenating, one (or several) empty line is equivalent to a semicolon, which would indicate the start of a new row.

    Consequently,

    c = {{1} {2}
    
         {3} {4}}
    

    results in a 2-by-2 array, and is equivalent to

    c = {{1},{2};{3},{4}}
    

    When you put a semicolon after each line

    c = {...
        {1};... 
        {2};... 
        {3};... 
        {4};...
        {5};... 
        }
    

    any commented-out line will be equivalent to a semicolon, and since multiple semicolons are legal (c = {{1};;{2};} works), you can now comment out any number of lines.

    Note that the output is now a n-by-1 instead of 1-by-n array, and that you shouldn't call it cell, since that is the name of a built-in function.