how do i reverse a vector
Mostrar comentarios más antiguos
so far i have this
function [Vout]=reverse(Vin)
Respuesta aceptada
Más respuestas (5)
Royi Avital
el 13 de Jun. de 2011
This might work as well (For 1D Vectors):
vReversed = v(end:-1:1);
Good luck!
3 comentarios
Shweta Kanitkar
el 29 de Mayo de 2013
v(end:-1:1) subtracts each element from v(end) by 1.
Walter Roberson
el 28 de Jun. de 2013
Matt Eicholtz points out that Shweta's comment is incorrect; no subtraction is done, only indexing.
Cyrus David Pastelero
el 8 de Jul. de 2020
This is what I am looking for. Thank you.
Walter Roberson
el 13 de Jun. de 2011
2 votos
fliplr() or flipud()
... But I suspect this is a class assignment. You will need to use your knowledge of MATLAB indexing and looping to work out your assignments for yourself.
goga
el 19 de Nov. de 2011
1 voto
use fliplr()
v = [1 2 3 4 5];
reversed = flip(v);
disp(reversed);
v = [10, 20, 30, 40, 50];
n = length(v);
for i = 1:n
rev(i) = v(n - i + 1);
end
disp('Reversed vector:');
disp(rev);
2 comentarios
Stephen23
el 28 de Jul. de 2026 a las 10:24
Doing this in a loop is very inefficient: avoid this approach!
It's also incorrect in some cases, since rev was not preallocated.
v = (1:5).'
n = length(v);
for i = 1:n
rev(i) = v(n - i + 1);
end
rev
whos v rev
In this case rev is the wrong size/shape! Compare with one of the recommended approach:
flippedV = flip(v)
whos flippedV v
In fact, the lack of preallocation may make the code error. Let me show the recommended approach first then show the error case. Because the previous section of code effectively "preallocated" rev, I need to clear it to simulate running the code in isolation.
v = zeros(1, 0);
flippedV = flip(v)
clear rev % Simulate running the code without preallocation
n = length(v);
for i = 1:n
rev(i) = v(n - i + 1);
end
rev % doesn't exist, so this will error
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!