how to create a loop for matrix iteration

40 次查看(过去 30 天)
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'];

回答(2 个)

Oleg Komarov
Oleg Komarov 2012-8-5
编辑:Oleg Komarov 2012-8-5
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 个评论
Fry
Fry 2012-8-5
thank you so much for helping me, I used the 3D double array method
Oleg Komarov
Oleg Komarov 2012-8-5
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
Azzi Abdelmalek 2012-8-5
编辑:Azzi Abdelmalek 2012-8-5
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,....

类别

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