Insert element in vector

104 次查看(过去 30 天)
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]

采纳的回答

Donald Baltus
Donald Baltus 2021-2-24
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
>>
  1 个评论
Rik
Rik 2021-2-24
Why are you dynamically growing the array? It seems much more efficient to use other methods, many of which are shown in the thread @Sugar Daddy linked.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

标签

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by