How do I add values to a list using indexes, when doing so changes the size of the list?

조회 수: 1 (최근 30일)
Title is a bit of a mouthful, but let me try to explain.
I have a long list of values about 130,000 values long, made up of 1s, 2s, 3s and 4s, as in:
sub = [1 1 2 3 4 4 3 4 3 2 1 3 1 1 2 3 3...];
I also have a list of indexes that correspond to this:
idx = [19 30 54 125 400 600 12030...]
The indexes are places at which I need to add in a zero value.
The thing is, I am not replacing the value at index 19 with the value 0, but rather, must add in the 0 at that point, so that it is the new index 19, and the old index 19 is now index 20.
I thought that I might have a solution to this here:
for k = 1:length(idx)
id = idx(k);
sub = [sub(1:id-1) 0 sub(id:end)];
idx = idx + 1;
end
Looking back at my example values in idx, the issue is when I add in a zero at say, index 19, the value that was at the old index 19 is now at index 20, 20 at 21, all the way down the line. That means that when we loop to index 30, the zero now needs to be at index 31, not 30. To resolve this, I simply added the idx+1, but this has resulted in the indexes in the list "idx" to past the last index of the list "sub".
What am I doing wrong here, and how do I resolve it?
  댓글 수: 2
Simon Chan
Simon Chan 2022년 1월 18일
Modify the first line inside the loop as follows and remove the last line
id = idx(k)+k-1
David Haydock
David Haydock 2022년 1월 18일
Worked like a charm, thankyou! Add it as an answer and I'll accept it.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by