# how to create a loop for matrix iteration

Asked by Fry on 5 Aug 2012
Latest activity Commented on by Oleg Komarov on 5 Aug 2012

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'];
```

## Products

No products are associated with this question.

Answer by Azzi Abdelmalek on 5 Aug 2012
Edited by Azzi Abdelmalek on 5 Aug 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,....```

## 1 Comment

Oleg Komarov on 5 Aug 2012

Please do not suggest eval() methods.

Answer by Oleg Komarov on 5 Aug 2012
Edited by Oleg Komarov on 5 Aug 2012

DO NOT do that!

Read this FAQ: How can I create variables A1, A2,...,A10 in a loop?

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
```

Azzi Abdelmalek on 5 Aug 2012

i read the problems occuring with eval, mainly with compiler. what i'am asking, is when it's recommanded to use eval? since in matlab help there is nothing about "eval will be removed".

Fry on 5 Aug 2012

thank you so much for helping me, I used the 3D double array method

Oleg Komarov on 5 Aug 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.