This error comes because you are trying to fill a variable chunk with more (or less) values than its size. In other words, you have a statement A(:)=B
on where size(A(:))
is different to size(B)
.
In the example in the question, rand(3)
returns a 3x3
matrix, however, output(ii)
is just a single value (even if output
may be bigger, output(ii)
is just a single value of output
), thus the value returned by rand(3)
does not fit inside output
.
In order to solve this problem, you need to change the the size of the output
variable, so you have space to fit all the result.
There are 2 ways of doing this. One of them is by creating a Matrix that fits the return, e.g. output=zeros(3,3,10)
.
Then we can change the code to
for ii= 1:10
output(:,:,ii)=rand(3);
end
Alternatively, you can fill the output
as a cell array. This is particularly useful when the return of the function changes sizes each time, e.g. rand(ii);
In that case, the following would work
for ii= 1:10
output{ii}=rand(ii);
end
It is probable that unlike in the example in the question, in the real case you do not know the size of what the output returns, thus you do not know which of the two options to use to fix your code.
On possible way of learning that, is activating debugging help when the code errors, by typing dbstop if error
in your command line. This will trigger a debugging stop when MATLAB throws an error, and you can type size(rand(ii))
and size(output(ii))
to see the sizes of both.
Often, reading the documentation of the function being used also helps, to see if different sizes are possible.
That said, the second option, cell arrays, will always ensure everything will fit. However matrices are generally a faster and easier to use in MATLAB, thus you should aim for the matrix based solution if you can.