How to insert a new vector to matrix in every iteration?

조회 수: 7 (최근 30일)
skinny pete
skinny pete 2019년 5월 18일
댓글: Sulaymon Eshkabilov 2019년 5월 18일
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?

채택된 답변

madhan ravi
madhan ravi 2019년 5월 18일
편집: madhan ravi 2019년 5월 18일
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
  댓글 수: 3
madhan ravi
madhan ravi 2019년 5월 18일
No I don’t and I don’t see how that’s related to the question you originally asked. You'd be better off posting a new question.
skinny pete
skinny pete 2019년 5월 18일
ok i will ask it a new asking page

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

추가 답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019년 5월 18일
편집: Sulaymon Eshkabilov 2019년 5월 18일
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
  댓글 수: 4
madhan ravi
madhan ravi 2019년 5월 18일
편집: madhan ravi 2019년 5월 18일
I just pointed out the fault which was there and there is no need to get angry with the fact being exposed. If it’s hard just ignore else try to accept the mistake and change it.
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019년 5월 18일
Thanks for clarifications.

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

카테고리

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