Flip a vector using for

10 visualizaciones (últimos 30 días)
The Canary Cry
The Canary Cry el 15 de Mzo. de 2018
Editada: Andrei Bobrov el 15 de Mzo. de 2018
I'm a MATLAB beginner in need of some help. I need to flip a vector so that it goes in reverse. Basically, [1 2 3] becomes [3 2 1]; Here's what I've got:
vector=[1:12]
A=0;
j=12;
for i=1:12
A=vector(i);
vector(i)=vector(j);
vector(j)=A;
j=j-1;
end
vector
I'm not really sure why it's not working since this seems like the logical way to do it.

Respuestas (2)

Andrei Bobrov
Andrei Bobrov el 15 de Mzo. de 2018
Editada: Andrei Bobrov el 15 de Mzo. de 2018
out = flip(yourvector);
with loop (no use)
out = zeros(size(yourvector));
k = 1;
for ii = numel(yourvector):-1:1
out(k) = yourvector(ii);
k = k + 1;
end
  1 comentario
The Canary Cry
The Canary Cry el 15 de Mzo. de 2018
Yes, I know there a functions to do it for me but I need to do it using for.

Iniciar sesión para comentar.


James Tursa
James Tursa el 15 de Mzo. de 2018
Editada: James Tursa el 15 de Mzo. de 2018
Because you are exchanging elements, you wind up flipping the vector twice, which gets it back to the original state. Instead, just run your for-loop through 1/2 of the vector so that the elements are only flipped once. E.g.,
for i=1:floor(numel(vector)/2)
  1 comentario
The Canary Cry
The Canary Cry el 15 de Mzo. de 2018
Oh! Yes, I see where I went wrong, thank you.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by