MATLAB: How to append multiple matrices in a loop

for loop

hello,
my code-
for ii=1:100
if ii=1
x=0;
else
for i=1:2:(((2^(ii-1))*2)-1)
if i==1
x=rand(2,2)
elseif i==(((2^(ii-1))*2)-1)
x=10*rand(2,2)
else
x=100*rand(2,2)
end
y=x
end
end
end
at y=x, i would like to append all the 2by2 matrices from the nested loop. how do i do that?

Best Answer

Using cat()
% following two are equavilant for concatenating along column
y = cat(1, y, x);
y = [y; x];
% following two are equavilant for concatenating along row
y = cat(2, y, x);
y = [y x];
Although if you can pre-allocate the space for y and use indexing, your code will be much faster. Read here: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html