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 argument v vector, while a,b, , c scalars. function replaces every element of v equal a b , c.

for example, command

x = replace_me([1 2 3],2,4,5); 

makes x equal [1 4 5 3]. if c omitted, replaces occurrences of a 2 copies of b. if b omitted, replaces each a 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

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -