how to create a loop for matrix iteration
39 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
hello everybody,
I'm beginner of matlab. I would like obtain z1, z2, z3 and z4 with a for loop, but I couldn't write it.
n=8;
p=5;
A=[1:n];
for k=2:p
for t=1:n
if (A(k-1,t)+1) < n+1
A(k,t)=A(k-1,t)+1;
else
A(k,t)=A(k-1,t)+1-n;
end
end
end
%how to write a loop for this part:
x=A(1,:);
y1=A(2,:);
y2=A(3,:);
y3=A(4,:);
y4=A(5,:);
z1=[x' y1'];
z2=[x' y2'];
z3=[x' y3'];
z4=[x' y4'];
0 Commenti
Risposte (2)
Oleg Komarov
il 5 Ago 2012
Modificato: Oleg Komarov
il 5 Ago 2012
DO NOT do that!
Use the cell array or the structure method.
Why should you avoid creating z1, z2, z3,...? You have to use eval() which is prone to error, it's more obscure, harder to debug but most importantly it's not a valid solution to project scalability. Every time you need to call a specific variable, you have to hardcode it and what if you had 100 variables, a nightmare!
EDIT 3 alternative methods which follow the suggestions in the FAQ
n = 8;
p = 5;
A = (1:n)';
% The cell array method
z = cell(p-1,1);
for ii = 1:p-1
z{ii} = [A A([ii+1:end, 1:ii])];
end
% The structure array method
for ii = 1:p-1
Z.(sprintf('z%d',ii)) = [A A([ii+1:end, 1:ii])];
end
% The 3D double array method (only if z1,z2... are matrices with same dimensions - I recommend this for your needs)
z = zeros(n,2,p-1);
for ii = 1:p-1
z(:,:,ii) = [A A([ii+1:end, 1:ii])];
end
3 Commenti
Oleg Komarov
il 5 Ago 2012
It's never recommended and mostly never needed.
Eval() and similar methods are necessary for swapping variables between different workspaces, unless you want to write on disk (not as fast as RAM, but I haven't tested SSD yet).
Basically eval() it's intuitive to the beginner (I myself used it a lot at the beginning) but a true pain once the code grows in dimension and complexity.
Azzi Abdelmalek
il 5 Ago 2012
Modificato: Azzi Abdelmalek
il 5 Ago 2012
n=8; p=5; A=[1:n];
for k=2:p
for t=1:n
if (A(k-1,t)+1) < n+1 A(k,t)=A(k-1,t)+1;
else A(k,t)=A(k-1,t)+1-n;
end
end
end
%how to write a loop for this part:
x=A(1,:);
for k=1:4
y.(sprintf('y%d',k))= A(k+1,:)
z.(sprintf('z%d',k))=[x' A(k+1,:)']
end
% your variables are y.y1, y.y2 ... and z.z1, z.z2,....
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!