Index the first maximum value in a sequence of consecutive numbers
1 回表示 (過去 30 日間)
古いコメントを表示
I have a column vector with the following sequences:
x = [0,0,1,1,1,2,0,1,2,2,3,3,3,3,3,0,0,0]';
I would like a logical vector a, equalizing 1 if it is equal to the first maximum value of the particular sequence of consecutive numbers (the sequences are separated by zeros), ie:
x = [0,0,1,1,1,2,0,1,2,2,3,3,3,3,3,0,0,0]';
a = [0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0]';
The code should be as efficient as possible (No loops).
1 件のコメント
Jos (10584)
2018 年 2 月 8 日
Homework? What have you tried so far?
Why are loops excluded? Often loops are most efficient ;)
採用された回答
Birdman
2018 年 2 月 9 日
Without for loop:
a=zeros(1,numel(x));
idx=find([0 diff(x)~=0]);
idxx=find(x(idx)==0)-1;
a(idx(idxx))=1
5 件のコメント
Jan
2018 年 2 月 9 日
@Birdman: For large x, the code find([0 diff(x)~=0]) can be slightly improved: If you concatenate two vectors, the resulting type is determined by the "larger" (concerning the class) one. diff(x)~=0 is a logical vector, but the initial 0 is a double. Then [0, diff(x)~=0] is a double vector, while [false, diff(x)~=0] would be a logical vector, which needs an 8th of the memory only.
The code fails for the input [3, 3, 0] due to a negative subscript. For [1, 2, 3] the output is [0,0,0], but this may be wanted.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Particle & Nuclear Physics についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!