matlabcell-arraypre-allocation

Why does matlab warn to preallocate a variable which is getting reset every loop?


There is a cell variable in my program which Matlab warns to preallocate it. The simple form of code is sth like this:

for i = 1:2
    a = [];
    a = [a,{'abc'}];
end

First I want to know why a should be preallocated, since it's getting reset in each loop. Second I don't know how to preallocate it. When I try to do so, Matlab gives me another warning, saying "The variable appears to be preallocated, but preallocation is not recommended here".

I use this code before the loop:

a = cell(1,2);

To be more specific:

for i = 1:2
    a = [];
    if condition1
        a = {'abc'};
    end
    if condition2
        a = [a,{'def'}];
    end
    b = [{'string'},a];
end

I want b to be a 1x1 cell array if the conditions are not true, so I need to reset a to an empty var in each loop.

Update:

I found a way, hinted by Lee's answer, but still doesn't know why. Using a = [a(:),{'def'}]; instead of a = [a,{'def'}]; solved the warning.


Solution

  • You made a a new variable, thus the former a = cell(1,2) was never used, which made matlab raised the warning.

    You can use sth like

    a = cell(1,2);
    for ii = 1:2
        a{ii} = 'abc';
    end
    

    or if you really want to change the size of a,

    for ii = 1:2
        a = {'a1'};
        a = [a(:); {'abc'}];
    end