How to Add Multiple Arrays?
조회 수: 7 (최근 30일)
이전 댓글 표시
I am new to matlab. I want to do the following: I had created nine arrays and gave each one a name from A to I, said: A,B,C,D,E,F,G,H,I. Once I done that what I want to do is add them in groups of three and put to each new array the name of the last array added. For example. array C=A+B+C, array F=D+E+F, array I=G+H+I, I want to do this using a for loop which I think will be the most practical way of do it.
Thank you
댓글 수: 0
채택된 답변
Oleg Komarov
2011년 3월 19일
If you could know how many matrices you have in advance (num), then preallocate before the loop:
dir1='C:\Documents and Settings\ann\My Documents\MATLAB\AMSR-E';
A = zeros(586,1383,num);
c = 1;
for year=2010:2010
for month=10:12
for day=1:eomday(year,month)
dd = [num2str(year),'.',num2str(month,'%0.2d'),...
'.',num2str(day,'%0.2d')];
file1 = ls([dir1,'\',dd,'\*.hdf']);
A(:,:,c) = hdfread([dir1,'\',dd,'\',file1],...
'Ascending_Land_Grid',...
'Fields', 'A_Veg_Water_Content');
% Increase counter
c = c+1;
end
end
end
You'll end up with a 3d array.
EDIT
Then to consolidate as Sean suggested use sum(A,3) in a loop:
A = rand(586,1383,8);
% Number of days to consolidate each time
n = 3;
% Final amount of slices
sl = ceil(size(A,3)/n);
% Preallocate
B = zeros(586,1383,sl);
for s = 1:sl-1
B(:,:,s) = sum(A(:,:, (s-1)*n+1:s*n ), 3);
end
% Final slice can be the result of less than 3 days
B(:,:,s+1) = sum(A(:,:,s*n+1:end),3);
Oleg
댓글 수: 3
Oleg Komarov
2011년 3월 19일
If you have NaNs then you should consider how to treat them, otherways they'll propagate causing loss of info.
추가 답변 (2개)
Andrew Newell
2011년 3월 19일
It's not clear to me why you want loops. As long as the arrays are the same size, you can just enter the equations the way you wrote them above, e.g.,
C = A+B+C
and it will work.
Sean de Wolski
2011년 3월 19일
doc cat
doc sum
댓글 수: 2
Matt Tearle
2011년 3월 19일
When you say "alternatively", do you mean "columns rather than rows" or "alternating columns"?
Former: sum(A,2)
Latter: sum(A(:,1:2:end))
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!