Search code examples
arraysmatlabvectorindexingassignment-operator

Substitute a vector value with two values in MATLAB


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

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

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.

How can I do this in MATLAB?


Solution

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

    Like rayryeng's solution, it can replace multiple occurrences of a.

    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.