how to create a loop for matrix iteration

조회 수: 34 (최근 30일)
Fry
Fry 2012년 8월 5일
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,....
  댓글 수: 1
Oleg Komarov
Oleg Komarov 2012년 8월 5일
Please do not suggest eval() methods.

댓글을 달려면 로그인하십시오.

카테고리

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