MATLAB: Shifting number to end of an array

for loopsshifting

Hi, I'm trying to write a function that takes an array (v) and a value(a) as its input then outputs an array(w). The output array takes any instance of the value out of its current position and moves it to the end of the array. This is a hw problem for school. My function works perfectly when the value a is nonzero but it doesn't work for zero values. I have included my function below. I'm afraid it's something with the for loop and iterating through it. I'm pretty new to Matlab and can't figure this out. Thanks!
function v=move_me(v,a)
if nargin<2
a=0;
end
ii=0;
for ii=1:length(v)
if ii==a
v(ii)=[]
v(end+1)=a;
w=v;
end
end
if true
% code
end

Best Answer

See if changing your if test to:
if v(ii)==a
helps.