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!