在 Matlab 中用两个值替换索引

Replacing an index with two values in Matlab

我试图在 Matlab 中解决以下问题:

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 [result] = replace_me(v,a,b,c)
    result = v;
    for ii = 1:length(v)
        if result(ii) == a
            result(ii) = b;
            result(ii +1) = c;
        end
    end
end

该函数将 v 中与 a 相同的值替换为 b,但我无法将 a 替换为 bc。任何帮助将非常感激。

编辑:

我更新了我的代码:

function [v] = replace_me(v,a,b,c)
for ii = 1:length(v)
  if v(ii) == a
    v = horzcat(v(1:ii-1), [b c], v(ii+1:end));
    fprintf('%d',v);
  elseif v(ii) == a && length(varargin) == 3
    v = horzcat(v(1:ii-1), [b b], v(ii+1:end));
    fprintf('%d',v);
  elseif v(ii) == a && 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

我尝试 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.

可以这样:

function result = replace_me(v, a, b, c)
  result = [];
  for ii = 1:length(v)
    if v(ii) == a
      result = [result, b, c];
    else
      result = [result, v(ii)];
    end
  end
end

关于错误"Error using replace_me (line 4) Not enough input arguments.",这仅仅是因为你写了4个输入参数的函数,而你只调用了3个。

通过计算 av 中出现的次数,您可以计算结果向量 length(v) + sum(v == a) 的大小,然后您可以遍历向量并插入 [b c] 每次找到匹配项。每次插入新元素时,您应该将计数器 ii 增加 2,否则如果 a=b,您将用 a 填充向量的剩余部分。这不是一个有效的算法,但它类似于您的实现

result = v;
rep = sum(result == a);

if rep == 0
  return
end

for ii = 1:(length(result) + rep)
  if result(ii) == a
    result = [result(1:ii-1), [b c], result(ii+1:end)];
    ii = ii + 2;
  end
end

一个有效的替代方案(不调整矢量大小)可以是:

rep = sum(v == a);

if rep == 0
    result = v;
    return;
end

result = zeros(1, length(v) + rep);

idx = 1;
for ii = 1:length(v)
    if v(ii) == a
       result(idx) = b;
       result(idx+1) = c;
       idx = idx + 2;
    else 
       result(idx) = a;
       idx = idx + 1;
    end
end

这里有一个替代方案:(@A.Donda 最初

这具有替换多次出现的优点

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

结果:

>> 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