MATLAB: Insert element in vector

MATLABvectors

The vector A consist of 223 elements of zeros and other values.
When a value above zero show up, I want to add one/several elements after it, for example -1.
A=[0 0 0 2 0 0 0 3 0 0 1];
becomes
A=[0 0 0 2 -1 0 0 0 3 -1 -1 0 0]

Best Answer

It seems you want to conditionally insert values into a vector.
You can insert values into a vector by using concat to reconstruct the original vector with modifications as desired. For example, to just duplicate a vector you could write a function:
function vectorOut = copyVector(vectorIn)
vectorOut = [];
for i = 1:numel(vectorIn)
item = vectorIn(i);
vectorOut = [vectorOut, [item]];
end
end
>> copyVector([0 1 2 0 3])
ans =
0 1 2 0 3
>>
You can do something other than just copy each element verbatim however. This function will return the original vector but with each element repeated once:
function vectorOut = repeatVector(vectorIn)
vectorOut = [];
for i = 1:numel(vectorIn)
item = vectorIn(i);
vectorOut = [vectorOut, [item item]];
end
end
>> repeatVector([0 1 2 0 3])
ans =
0 0 1 1 2 2 0 0 3 3
>>
Finally, you can generalize the function by passing a function argument specifying the insertion behavior:
function vectorOut = modifyVector(vectorIn, modifyFunction)
vectorOut = [];
for i = 1:numel(vectorIn)
item = vectorIn(i);
vectorOut = [vectorOut, modifyFunction(item)];
end
end
>> modifyVector([0 1 2 0 3], @(x) x+100)
ans =
100 101 102 100 103
>>
If you write a specialized modify function, you can get the behavior you want:
function replacement = insertIfNotZero(item)
if item ~= 0
replacement = [item -1];
else
replacement = [item];
end
end
>> modifyVector([0 1 2 0 3], @insertIfNotZero)
ans =
0 1 -1 2 -1 0 3 -1
>>