Flip a vector using for

6 次查看(过去 30 天)
The Canary Cry
The Canary Cry 2018-3-15
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.

回答(2 个)

Andrei Bobrov
Andrei Bobrov 2018-3-15
编辑:Andrei Bobrov 2018-3-15
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 个评论
The Canary Cry
The Canary Cry 2018-3-15
Yes, I know there a functions to do it for me but I need to do it using for.

请先登录,再进行评论。


James Tursa
James Tursa 2018-3-15
编辑:James Tursa 2018-3-15
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)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by