MATLAB: Make many matrices with for loop

auto makematrix

Hi
I have problem with making matrices with for loop
I want to make 272 matrices by automatically. for example
Band1=[~~~] Band2=[~~~] Band3=[~~~] . . . Band272=[~~~]
here is my code that I made. and r= 2000, c=640 , b=272
a=geotiffread('D:\Junsu2\3rd semester\hangigong\tiff\13118.tif');
[r,c,b]= size(a);
for bandno=1:b
for i=1:r
for j=1:c
Band{bandno}(i,j)= a(i,j,bandno);
end
end
end
please help me I dont want to right 272times to make matrices.
Thank you

Best Answer

It is easy to split an MxNxP array into P separate arrays: just use num2cell. Note that MATLAB is a high-level language, so solving everything with lots of ugly loops like in low-level languages (like C++) is not required.

You just need to use num2cell like this:

a = geotiffread(...);
c = num2cell(a,1:2);

Each MxN matrix is in one cell of the cell array c. You can access them trivially and efficiently using cell array indexing:

c{1}
c{2}
c{3}
...

Personally I would not bother splitting up the data like this: the data is already stored in a perfectly good 3D numeric array, which you can access trivially and efficiently using indexing:

a = geotiffread(...);
for k = 1:size(a,3);
     a(:,:,k)
end

and also you can perform operations on the entire data using vectorized code. Also when you split this array into lots of matrices you create superfluous duplicate copies of the data in memory. In general it is better to keep data together as much as possible, rather than splitting it apart. I don't see any advantage in splitting up this array.