Move element to the end of the vector.

조회 수: 3 (최근 30일)
Ioannis Georgopoulos
Ioannis Georgopoulos 2018년 4월 20일
댓글: Ioannis Georgopoulos 2018년 4월 20일
Hi there.
I am trying to create a function that moves every element of 'v' that is equal to 'a' to the end of the vector. Argument 'v' is the first input and it is a row-vector, while 'a' is a scalar. For example, the command
>> x = move_me([1 2 3 4],2);
makes x equal to [1 3 4 2]
So my function so far looks like this:
function w=moveme(v,a)
for ii=1:length(v)
if v(ii)==a
w=[v(v~=a) v(v==a)];
end
end
and seems to work fine. But when I add an extra component to account for the scenario in which no element equals 'a' then my function doesn't work:
for ii=1:length(v)
if v(ii)==a
w=[v(v~=a) v(v==a)];
else
w=v;
end
end
What am I missing here?

채택된 답변

Matt J
Matt J 2018년 4월 20일
편집: Matt J 2018년 4월 20일

Your loop index ii is not being used. There is no need to use a loop anyway. It can be done in one line:

function w=moveme(v,a)
     w=[v(v~=a),  v(v==a)];
  댓글 수: 1
Ioannis Georgopoulos
Ioannis Georgopoulos 2018년 4월 20일
Thank you Matt for your prompt reply.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by