Insert element in vector
100 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joel Schelander
am 24 Feb. 2021
Kommentiert: Rik
am 24 Feb. 2021
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]
1 Kommentar
Akzeptierte Antwort
Donald Baltus
am 24 Feb. 2021
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 Kommentar
Rik
am 24 Feb. 2021
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu MATLAB Coder finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!