代替一个矢量值与在MATLAB两个值 [英] Substitute a vector value with two values in MATLAB

查看:99
本文介绍了代替一个矢量值与在MATLAB两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个函数,需要输入一个向量 v 和三个标量 A b C 。该函数替换的每一个元v 等于 A 用两元素数组 [ b,C]

I have to create a function that takes as input a vector v and three scalars a, b and c. The function replaces every element of v that is equal to a with a two element array [b,c].

例如,由于 V = [1,2,3,4] A = 2,B = 5,c = 5 ,输出将是:

For example, given v = [1,2,3,4] and a = 2, b = 5, c = 5, the output would be:

out = [1,5,5,3,4]

我第一次尝试是试图这样的:

My first attempt was to try this:

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

不过,我得到一个错误,所以我不明白如何把两个值之一发生在一个载体,即一个位置偏移以下所有值向右,使新的两个值适合在矢量和,因此,向量的大小将在一个增加。此外,如果有几个值 A 中存在的 v ,我不知道如何来代替它们一次全部。

However, I get an error, so I do not understand how to put two values in the place of one in a vector, i.e. shift all the following values one position to the right so that the new two values fit in the vector and, therefore, the size of the vector will increase in one. In addition, if there are several values of a that exist in v, I'm not sure how to replace them all at once.

如何在MATLAB做到这一点?

How can I do this in MATLAB?

推荐答案

下面使用电池阵列的解决方案:

Here's a solution using cell arrays:

% 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);

像rayryeng的解决方案,它可以代替 A 多次出现。

由siliconwafer提到的问题,即在阵列的变化的大小,在这里通过的中等保持部分阵列中一个单元阵列的细胞解决。转换回一个数组concenates这些部分。

The problem mentioned by siliconwafer, that the array changes size, is here solved by intermediately keeping the partial arrays in cells of a cell array. Converting back to an array concenates these parts.

这篇关于代替一个矢量值与在MATLAB两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆