Here the code that i have as example:
aaa = [];
bbb = [];
for ii = 1:10
[aaa(:,:,end+1), bbb(:,end+1)] = myfunction();
end
The function myfunction:
function [aaa, bbb] = myfunction()
aaa = rand(5,3);
bbb = rand(5,1);
end
I know i could use ii for sending the output from the variables to aaa and bbb like [aaa(:,:,ii), bbb(:,ii)] = myfunction(). I'm just curious to know why for aaa i generate a 5x3x11 matrix (shouldn't it be 5x3x10?)?. For bbb, it correctly generates a 5x10 matrix. Hence, why the end + 1 works for bbb and not aaa?
I believe this has to do with how MATLAB defines an empty matrix. If you do size(aaa), MATLAB will return 0 0, as you would expect. size(bbb) returns the same. However, if you explicitly try to find the size of the 3rd dimension using size(aaa,3), MATLAB returns 1. So it appears that MATLAB defines an empty matrix as having zero size in the first two dimensions, and a size of 1 in all the other dimensions.
What this means is that when you do a(:,:,end+1), you're actually accessing a(:,:,2), because the end of the 3rd dimension of a is 1, even when it is empty. You don't have this problem with b, because it is only two dimensional, and the end of the second dimension of an empty matrix is zero.
EDIT: As an aside, you should always pre-allocate your matrices if you're going to be assigning values to them in a loop (MATLAB will have complained about this, I believe). If you don't, the matrices have to be resized on every loop iteration, generally resulting in a slower execution time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With