Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Problems with for loop

조회 수: 1 (최근 30일)
cyberdyne
cyberdyne 2011년 6월 3일
마감: MATLAB Answer Bot 2021년 8월 20일
Hi,
I've a column vector q with 137 elements. I want generate a row vector Q
Q=[q(i) 0] taking elements of q one by one. I've tried by a for loop in this way:
for i=1:137
Q=[q(i) 0];
end
but it returns only the last element of q. This's q(137) in Q.
How can i set it for all elements of q ?

답변 (4개)

Andrei Bobrov
Andrei Bobrov 2011년 6월 3일
more
Q = zeros(1,2*length(q));
Q(1:2:end) = q

Walter Roberson
Walter Roberson 2011년 6월 3일
Q = reshape([q(:),zeros(numel(q),1)],1,[]);
or
Q = q(:);
Q(1,2) = 0; %expands to 2 columns
Q = reshape(Q,1,[]); %row vector
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 6월 3일
Ah, you are right. Okay, that leads to
Q = q(:).';
Q(2,1) = 0;
Q = reshape(Q,1,[]);
or
Q = reshape([q(:),zeros(numel(q),1)].',1,[]);
Walter Roberson
Walter Roberson 2011년 6월 3일
or
Q = reshape([q(:).';zeros(1,numel(q))],1,[]);

Sean de Wolski
Sean de Wolski 2011년 6월 3일
To fix this you would need:
for ii = 1:137 %don't use i, it's the sqrt(-1)
Q(ii*2-1:ii*2) = [q(ii) 0];
end
Walter's solution is the best way to do this, however.

cyberdyne
cyberdyne 2011년 6월 4일
Thanks at all !!! ^^

이 질문은 마감되었습니다.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by