How to call up matrices in a loop

조회 수: 4 (최근 30일)
Ian
Ian 2013년 9월 15일
I have 960 matrices labelled as follows:
A1 A2 A3.....A959 A960;
Is there a way of calling up all this matrices in a loop as I want to add them up as follows:
B=A1+A2+A3
but then carry on adding the next 3 matrices and so on.
I have tried:
for 1:960
B=(A(i)+A(i+1)+A(i+2));
end
I am fairly new to matlab so I apologise if this seemd straight forwrad

답변 (3개)

Matt J
Matt J 2013년 9월 15일
편집: Matt J 2013년 9월 15일
You should regenerate your matrices as slices of a 3D array
A(:,:,1), A(:,:,2),..., A(:,:,960)
Aside from making the data easier to index, the summation you mention can then be done by simple convolution,
e=reshape( ones(1,3), 1,1,[]);
B=convn(A,e,'valid');

Markus
Markus 2013년 9월 15일
편집: Markus 2013년 9월 15일
you need the command 'eval' this is one universal solution, you just have to make sure than only the martices which you wanna combine are in the workspace (eg. with the command load('matlabFile.mat', 'A*'):
clear
% load('matlabFile.mat', 'A*');
A1=rand(3,3);
A2=rand(3,3);
A3=rand(3,3);
A4=rand(3,3);
Axxx=who;
B=zeros(3);
for i=1:length(Axxx)
s=['B=[B+' char(Axxx(i,1)) '];'];
eval(s)
end
if you wanna stick to the numbers - it should work this way:
clear
A1=rand(3,3);
A2=rand(3,3);
A3=rand(3,3);
A4=rand(3,3);
B=zeros(3);
for i=1:4 % you might need to know or check how many variables you have.
s=['B=[B+A' num2str(i) '];']
eval(s)
end
  댓글 수: 4
Matt J
Matt J 2013년 9월 15일
The OP talked about indexing and summing subsets of A1...A960, not combining them into one. If the code that generated A1...A960 is no longer available, I have agreed that you would be forced to manipulate the data using EVAL. Otherwise it would be better to correct that original code and recreate the data as
A(:,:,1), A(:,:,2),..., A(:,:,960)
If using EVAL to combine the data, though, I would avoid growing B in the loop and do this instead
N=960;
B=zeros([size(A1),N]);
for i=1:N
s=['A' num2str(i)];
B(:,:,i)=eval(s);
end
Markus
Markus 2013년 9월 17일
you're right. i like your solution. :)

댓글을 달려면 로그인하십시오.


Jan
Jan 2013년 9월 17일
Hiding indices in the names of variables is a bad idea. Better use an index as index: see http://www.mathworks.com/matlabcentral/answers/57445-faq-how-can-i-create-variables-a1-a2-a10-in-a-loop

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by