Insert element in vector
103 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Joel Schelander
el 24 de Feb. de 2021
Comentada: Rik
el 24 de Feb. de 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 comentario
Respuesta aceptada
Donald Baltus
el 24 de Feb. de 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 comentario
Rik
el 24 de Feb. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre MATLAB Coder en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!