Asked by skinny pete
on 18 May 2019

Hi everyone,

I try to form a matrix that gets the vector elements by using for loop. In other words, I want to save the for loop result in a matrix. You can see my code below and what I want.

for x=1:1:3

for y=4:1:5

z = [x y]'

????

end

end

out =

1 1 2 2 3 3

4 5 4 5 4 5

Could you help me about this 2x6 matrix, please?

Answer by madhan ravi
on 18 May 2019

Edited by madhan ravi
on 18 May 2019

Accepted Answer

Trivially done without a loop:

out = [repelem(x,1:numel(x));repmat(y,1,numel(x))]

With loop:

x=1:3;

y=4:5;

ctr=1;

out=zeros(2,numel(x)+numel(y)); % preallocate!

for k=1:numel(x)

for l=1:numel(y)

out(:,ctr) = [x(k) ; y(l)];

ctr=ctr+1;

end

end

Gives:

>> out

out =

1 1 2 2 3 3

4 5 4 5 4 5

skinny pete
on 18 May 2019

Thank you for your answer Mr. Ravi. It works well. The purpose of the find this matrix is to plot a polygon using x and y coordinates. When I did it, I got the polygon that I do not want with several intersections due to array of the elements in the out matrix. You can see the below. So, How can I arrange of the elements' array to get smooth polygon. Do you have any idea?

pgon = polyshape([out(1,:)], [out(2,:)]);

plot(pgon)

grid on

madhan ravi
on 18 May 2019

skinny pete
on 18 May 2019

ok i will ask it a new asking page

Sign in to comment.

Answer by Sulaymon Eshkabilov
on 18 May 2019

Edited by Sulaymon Eshkabilov
on 18 May 2019

This one works:

x = [1 1 2 2 3 3];

y= [4 5 4 5 4 5];

z = zeros(2, numel(x));

for ii=1:numel(x)

z(:,ii)=[x(ii), y(ii)];

end

madhan ravi
on 18 May 2019

And ofcourse you're a genius :)

madhan ravi
on 18 May 2019

Sulaymon Eshkabilov
on 18 May 2019

Thanks for clarifications.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.