how to create a loop for matrix iteration

29 ビュー (過去 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 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