How to call up matrices in a loop
4 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(3 个)
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
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!