How to remove sets of values from a column vector using two column vectors with the starting and stopping indeces for removal by row

1 回表示 (過去 30 日間)
Let's say that I have a column vector, x
x = (1:10)'
and two column vectors with the starting and stopping indeces, x_start and x_stop
x_start = [2; 7]
x_stop = [5; 8]
such that I want to remove the values 2->5 and 7->8.
I could use a simple for loop, such as the following:
for i = length(x_start):1
a = x_start(i)
b = x_stop(i)
x(a:b) = []
end
However, I would look to avoid using a for loop as my vector lengths are on the order of 10^5. Is there a more computationally efficient manner to build the indeces that I want to remove from my starting and stopping vectors?
  2 件のコメント
Fangjun Jiang
Fangjun Jiang 2016 年 8 月 2 日
There is a typo. Should be
for i = length(x_start):-1:1
Shawn
Shawn 2016 年 8 月 2 日
Ah yes, you are correct. Thanks for noting that.

サインインしてコメントする。

採用された回答

Fangjun Jiang
Fangjun Jiang 2016 年 8 月 2 日
This method uses string. Not sure if it is more efficient.
num=[x_start,x_stop]';
str=sprintf('%d:%d,',num(:));
x(str2num(str))=[];
  2 件のコメント
Shawn
Shawn 2016 年 8 月 2 日
This is an interesting answer, but it does not seem to be working for length(x_start)~=2.
If I use x_start and x_stop with length 3 as:
x_start = [1,4,9]
x_stop = [2,7,10]
Then I return x = [5,6], but it should return x = [3,8] if I am removing 1->2, 4->7, and 9->10.
In this case, str = '1:4,9:2,7:10' rather than '1:2,4:7,7:10'. It does work on the length 2 case, but that was just pseudo-code to explain the problem. The actual vectors are much larger. Can this approach be expanded to account for that?
Shawn
Shawn 2016 年 8 月 2 日
I apologize, I forgot to transpose the x_start and x_stop vectors. The code seems to be running well. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by