Something I would like to do is first find the values โโof v that are equal to a , which we will call ind . Then create a new output vector whose output file size is numel(v) + numel(ind) , since we replace every value of a that is in v with an extra value, then use indexing to put our new values โโin.
Assuming you created a line vector v , follow these steps:
%// 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);
The indx and indy operators are quite complex, but certainly not hard to understand. For each index in v equal to a , what happens is that we need to shift the vector by 1 for each index / location v equal to a . The first value requires that we move the vector to the right by 1, then the next value requires that we shift to the right by 1 relative to the previous shift , which means that we really need to take the second pointer and shift right by 2, as this applies to source index.
The following value requires that we shift to the right by 1 relative to the second shift or shift to the right by 3 relative to the original index, and so on. These shifts determine where we are going to place b . To place c , we simply take the indices created to place b and move them to the right by 1.
It remains to fill the output vector with those values โโthat are not equal to a . We simply define a logical mask in which the indices used to populate the output array have their locations set to false and the rest to true . We use this to index into the output and find those locations that are not equal to a to complete the assignment.
Example:
v = [1,2,3,4,5,4,4,5]; a = 4; b = 10; c = 11;
Using the code above, we get:
out = 1 2 3 10 11 5 10 11 10 11 5
This successfully replaces each value equal to 4 in v , with a tuple [10,11] .