How to call up matrices in a loop

5 次查看(过去 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