How to call up matrices in a loop
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Matt J
am 15 Sep. 2013
Bearbeitet: Matt J
am 15 Sep. 2013
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');
0 Kommentare
Markus
am 15 Sep. 2013
Bearbeitet: Markus
am 15 Sep. 2013
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 Kommentare
Matt J
am 15 Sep. 2013
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
am 17 Sep. 2013
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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!