for loop - Replacing an index with two values in Matlab -
i'm attempting solve following problem in matlab:
the function
replace_me
defined this:function w = replace_me(v,a,b,c)
. first input argumentv
vector, whilea
,b
, ,c
scalars. function replaces every element ofv
equala
b
,c
.for example, command
x = replace_me([1 2 3],2,4,5);
makes
x
equal[1 4 5 3]
. ifc
omitted, replaces occurrences ofa
2 copies ofb
. ifb
omitted, replaces eacha
2 zeros."
here have far:
function [result] = replace_me(v,a,b,c) result = v; ii = 1:length(v) if result(ii) == result(ii) = b; result(ii +1) = c; end end end
the function replaces values in v
same a
b
, i'm not able replace a
both b
, c
. appreciated.
edit:
i have updated code:
function [v] = replace_me(v,a,b,c) ii = 1:length(v) if v(ii) == v = horzcat(v(1:ii-1), [b c], v(ii+1:end)); fprintf('%d',v); elseif v(ii) == && length(varargin) == 3 v = horzcat(v(1:ii-1), [b b], v(ii+1:end)); fprintf('%d',v); elseif v(ii) == && length(varargin) == 2 v = horzcat(v(1:ii-1), [0 0], v(ii+1:end)); fprintf('%d',v); else fprintf('%d',v); end end end
i receive following error when try replace_me([1 2 3 4 5 6 7 8 9 10], 2, 2):
replace_me([1 2 3 4 5 6 7 8 9 10],2,2) 12345678910 error using replace_me (line 4) not enough input arguments.
here alternative: (originally answered @a. donda)
this has advantage of replacing multiple occurrences
function [result] = replace_me(v,a,b,c) if nargin == 3 c = b; end if nargin == 2 c = 0; b = 0; end result = v; equ = result == a; result = num2cell(result); result(equ) = {[b c]}; result = [result{:}]; end
results:
>> x = replace_me([1 2 3],2,4,5) x = 1 4 5 3 >> x = replace_me([1 2 3],2) x = 1 0 0 3 >> x = replace_me([1 2 3],2,4) x = 1 4 4 3 >> x = replace_me([1 2 3 2], 2, 4, 5) x = 1 4 5 3 4 5
Comments
Post a Comment