Extracting the first contiguous values without looping

10 ビュー (過去 30 日間)
Noel Khan
Noel Khan 2014 年 3 月 24 日
コメント済み: Noel Khan 2014 年 3 月 25 日
Hi everyone,
I need to make a decision based values in a matrix and would like to avoid nested loops. I used arrayfun to produce a matrix of boolean values, but am only interested in the first set of contiguous truths . So, for example, if:
A = [ 1 1 0 0 1 1;
0 0 1 1 1 0;
1 0 1 1 0 0;
0 0 1 1 1 1]
B = [ 1 1 0 0 0 0; % first two bits retained
0 0 1 1 1 0; % unch
1 0 0 0 0 0; % only first bit retained
0 0 1 1 1 1] % unch
The options I've come up with are a bit caddy-whompus and are row-based, so they're no good. These involved (1) casting / strfind or (2) find (first 1 in B, then subsequent 0 in ~B).
Any suggestions?
Regards,
Noel

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 3 月 24 日
編集済み: Azzi Abdelmalek 2014 年 3 月 24 日
A = [ 1 1 0 0 1 1;
0 0 1 1 1 0;
1 0 1 1 0 0;
0 0 1 1 1 1]
B=diff(A,[],2)
[n,m]=size(A);
idx=arrayfun(@(x) min([find(B(x,:)==-1,1)+1 m+1]),1:n)
for k=1:n
A(k,idx(k):end)=0
end
%Or
A = [ 1 1 0 0 1 1;
0 0 1 1 1 0;
1 0 1 1 0 0;
0 0 1 1 1 1]
B=diff(A,[],2)
[n,m]=size(A);
idx=arrayfun(@(x) min([find(B(x,:)==-1,1)+1 m+1]),1:n)
ii=cell2mat(arrayfun(@(x) [idx(x):m;x*ones(1,m-idx(x)+1)],1:n,'un',0))
jj=sub2ind(size(A),ii(2,:),ii(1,:))
A(jj)=0
  2 件のコメント
Noel Khan
Noel Khan 2014 年 3 月 24 日
Thank you for the prompt reply!
Noel Khan
Noel Khan 2014 年 3 月 25 日
Azzi's code has a lot of gems -- it took a few rounds between the docs and tinkering to understand what it was doing. For those working on a similar problem here's the code (largely Azzi's) I'm running with:
A =
1 1 0 0 1 1
0 0 1 1 1 0
1 0 1 1 0 0
0 0 1 1 1 1
B=diff(A,[],2);
[m,n]=size(A);
idx=arrayfun(@(x) min([find(B(x,:)==-1,1) n]), 1:m);
cell2mat(arrayfun(@(x) [A(x,1:idx(x)),zeros(1,n-idx(x))], 1:m, 'UniformOutput', 0)')
ans =
1 1 0 0 0 0
0 0 1 1 1 0
1 0 0 0 0 0
0 0 1 1 1 1
Thanks again Azzi!
Regards,
Noel

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by