Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Problems with for loop

1 visualización (últimos 30 días)
cyberdyne
cyberdyne el 3 de Jun. de 2011
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
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 ?

Respuestas (4)

Andrei Bobrov
Andrei Bobrov el 3 de Jun. de 2011
more
Q = zeros(1,2*length(q));
Q(1:2:end) = q

Walter Roberson
Walter Roberson el 3 de Jun. de 2011
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 comentarios
Walter Roberson
Walter Roberson el 3 de Jun. de 2011
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 el 3 de Jun. de 2011
or
Q = reshape([q(:).';zeros(1,numel(q))],1,[]);

Sean de Wolski
Sean de Wolski el 3 de Jun. de 2011
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 el 4 de Jun. de 2011
Thanks at all !!! ^^

La pregunta está cerrada.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by