在MATLAB中用两个值替换向量值

Mar*_*tro 5 arrays indexing matlab vector assignment-operator

我要创建一个函数,需要输入一个向量v和三个标量a,bc.的函数替换的每一个元素v等于a具有两个元件阵列[b,c].

例如,给定v = [1,2,3,4]a = 2, b = 5, c = 5,输出将是:

out = [1,5,5,3,4]
Run Code Online (Sandbox Code Playgroud)

我的第一次尝试是试试这个:

v = [1,2,3,4];
v(2) = [5,5];
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个错误,所以我不明白如何将两个值放在向量中的一个位置,即将所有以下值移到一个位置向右,以便新的两个值适合向量,因此,矢量的大小将增加一个.此外,如果有几个值a都存在于v,我不知道如何一次性全部更换.

我怎样才能在MATLAB中做到这一点?

A. *_*nda 6

这是使用单元格数组的解决方案:

% remember the indices where a occurs
ind = (v == a);
% split array such that each element of a cell array contains one element
v = mat2cell(v, 1, ones(1, numel(v)));
% replace appropriate cells with two-element array
v(ind) = {[b c]};
% concatenate
v = cell2mat(v);
Run Code Online (Sandbox Code Playgroud)

像rayryeng的解决方案,它可以取代多次出现a.

硅晶片提到的问题,即阵列改变尺寸,这里通过将部分阵列中间保持在单元阵列的单元中来解决.转换回数组会使这些部分变得模糊.


ray*_*ica 5

我要做的是首先找到它们的值v等于a我们将要调用的值ind.然后,创建具有输出大小等于新的输出向量numel(v) + numel(ind),因为我们正在取代的每个值a是在v与另外的值,然后使用索引来放置我们的新值英寸

假设您已创建向量v,请执行以下操作:

%// Find all locations that are equal to a
ind = find(v == a);

%// Allocate output vector
out = zeros(1, numel(v) + numel(ind));

%// Determine locations in output vector that we need to
%// modify to place the value b in
indx = ind + (0:numel(ind)-1);

%// Determine locations in output vector that we need to
%// modify to place the value c in
indy = indx + 1;

%// Place values of b and c into the output
out(indx) = b;
out(indy) = c;

%// Get the rest of the values in v that are not equal to a
%// and place them in their corresponding spots.
rest = true(1,numel(out));
rest([indx,indy]) = false;
out(rest) = v(v ~= a);
Run Code Online (Sandbox Code Playgroud)

indxindy语句是相当棘手的,但肯定也就不难理解了.对于每个v等于的索引a,我们需要将每个索引/位置v等于1的向量移过1 a.第一个值要求我们将向量向右移动1,然后下一个值要求我们相对于前一个移位向右移动1 ,这意味着我们实际上需要采用第二个索引并转换为右边2,因为这是关于原始索引.

下一个值要求我们相对于第二个移位向右移动1,或者相对于原始索引向右移动3,依此类推.这些转变定义了我们将要放置的位置b.要放置c,我们只需获取生成的索引进行放置,b然后将它们向右移动1.

剩下的就是用那些不相等的值填充输出向量a.我们只是定义一个逻辑掩码,其中用于填充输出数组的索引将其位置设置为,false而其余的设置为true.我们使用它来索引输出并找到那些不等于a完成赋值的位置.


例:

v = [1,2,3,4,5,4,4,5];
a = 4;
b = 10;
c = 11;
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我们得到:

out =

     1     2     3    10    11     5    10    11    10    11     5
Run Code Online (Sandbox Code Playgroud)

这成功地用v元组替换了每个4的值[10,11].