필터 지우기
필터 지우기

Insert element in vector

조회 수: 29 (최근 30일)
Joel Schelander
Joel Schelander 2021년 2월 24일
댓글: Rik 2021년 2월 24일
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개)

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by