Search Program on this blog

Wednesday 19 August 2015

The function replace_me is defined like this: function w = replace_me(v,a,b,c). The first input argument v is a vector, while a, b, and c are all scalars. The function replaces every element of v that is equal to a with b and c. For example, the command >> x = replace_me([1 2 3],2,4,5); makes x equal to [1 4 5 3]. If c is omitted, it replaces occurrences of a with two copies of b. If b is also omitted, it replaces each a with two zeros.

function w = replace_me(v,a,b,c)
%Input v is a vector, while a, b, and c are all scalars
%Output w is a vector
%Example: w = replace_me([1 2 3],2,4,5);
%         w = [1 4 5 3]
w=[];
if nargin==4
    for i=1:length(v)
        if v(i)==a
           w=[w b c];   %add b c to vector
        else
            r=v(i);
            w=[w r];
        end
    end
elseif nargin==3    %if c is omitted
    for i=1:length(v)
        if v(i)==a
            w=[w b b];   %add b b to vector
        else
            r=v(i);
            w=[w r];
        end
    end
elseif nargin==2    %if b is omitted
    for i=1:length(v)
        if v(i)==a
            w=[w 0 0]; %add 0 0 to vector
        else
            r=v(i);
            w=[w r];
        end
    end
end

No comments:

Post a Comment