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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by