Select every Nth row from number groups
3 ビュー (過去 30 日間)
古いコメントを表示
I have a vector that looks like
a = [1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 1....]
I would like to find the vector location where I would find the first 1, second 1, third 1 and so on, in the trains of 1's in a quickish way.
As an output... I would like new vectors containing only the first 1 in every sequence of 1's
eg
b = [1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0....]
c = [0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0....]
OR
a Matrix containing the locations of each number in a sequence...
b = [1 13 19]
c = [2 14 20]
d = [3 15 21].... and so forth
1 件のコメント
Ondrej
2015 年 1 月 20 日
Can you please clarify your question (maybe some example of what you expect)? Do you want the indices of all ones in the vector?, e.g.
a = [1 1 0 1], result = [1 2 4]
?
採用された回答
その他の回答 (3 件)
Ondrej
2015 年 1 月 20 日
編集済み: Ondrej
2015 年 1 月 20 日
If the n "trains" of ones have the same length always, then this probably what you want:
result = repmat(find(diff([0 a])==1),n,1)+(0:n-1)'*ones(1,n)
For example:
a = [1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1];
n = 3;
result = repmat(find(diff([0 a])==1),n,1)+(0:n-1)'*ones(1,n)
>> result =
1 13 21
2 14 22
3 15 23
UPDATE:
If the number of your outputs should be equal to the shortest length of the train of ones (in your case 3), then you have to find 'n', e.g.,
tmp = find(diff([0 a])==1);
n = min(find(diff([a 0])==-1) - tmp)+1;
m = length(tmp);
result = repmat(tmp,n,1)+(0:n-1)'*ones(1,m)
Elias Gule
2015 年 2 月 17 日
編集済み: Elias Gule
2015 年 2 月 17 日
a = [1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1];
isTake = false;
newMatrix = nan*ones(size(a)); count = 0;
for k = 1 : length(a) val = a(k);
if((val == 1) && ~isTake)
count = count + 1;
newMatrix(count) = k;
isTake = true;
else
isTake = (val == 1);
end
end
newMatrix = newMatrix(~isnan(newMatrix));
0 件のコメント
Jos (10584)
2015 年 2 月 17 日
a = [1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 1]
k = 1 ;
while any(a)
i0 = strfind([0 a],[0 1]) ;
OUT{k} = i0 ;
a(i0) = 0 ;
k = k + 1 ;
end
% OUT{X} holds those indices of A where a 1 occurs as the X-th element in the series of 1's
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!