Indexing & Move Me function
古いコメントを表示
function out = move_me(v,a)
lng = length(v);
for i = 1:lng;
%evaluating each position of v in relation to a
if v(i) == a;
%if the value is equal, I deleted the value to then move it to the
%back of the function
v(i) = [];
v(lng) = a;
elseif v ~= a
v = [v, zeros(1, i)];
end
end
out = v
end
"The function move_me is defined like this: function w = move_me(v,a). The first input argument v is a row-vector, while a is a scalar. The function moves every element of v that is equal to a to the end of the vector. For example, the command
>> x = move_me([1 2 3 4],2);
makes x equal to [1 3 4 2]. If a is omitted, the function moves occurrences of zeros."
When I run the code, if the vector contains more than one of the same value of a it only moves one of the values to the back. Also, when trying to add zeros to the back if the vector does not contain a, more zeros are added than needed. I'm not quite sure why it is not working. Should I make the elseif statement its own if statement?
採用された回答
その他の回答 (2 件)
Anupriya Krishnamoorthy
2018 年 2 月 17 日
編集済み: Anupriya Krishnamoorthy
2018 年 2 月 17 日
% code
function w = move_me(v,a)
if nargin < 2 % checks whether function input is less than 2
a = 0;
w = [v(v~=a) v(v==a)];
else
w = [v(v~=a) v(v==a)];
end
end
RAMAKANT SHAKYA
2019 年 2 月 7 日
function out= move_me(v,a)
s=length(v);
if nargin < 2 %for validation of input
a=0;
end
for x=1:s
if v(x)==a %comparing array element to the given no
t=x;
for y=t:s-1
v(y)=v(y+1); %shifting to right
end
v(s)=a;
end
out=v;
if v(x)==a
t=x;
for y=t:s-1
v(y)=v(y+1);%shifting to right
end
v(s)=a;
out=v;
end
if v(x)==a
t=x;
for y=t:s-1
v(y)=v(y+1);%shifting to right
end
v(s)=a;
out=v;
end
end
end
1 件のコメント
Walter Roberson
2019 年 2 月 8 日
Seems like a waste for something that can be implemented in one line by using logical indexing.
カテゴリ
ヘルプ センター および File Exchange で Downloads についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!