How can I find one index for each row of a 2d matrix where a condition is met?

조회 수: 3 (최근 30일)
funkadelala
funkadelala 2015년 2월 13일
댓글: Geoff Hayes 2015년 2월 21일
A is an n by n matrix. B is an n by 1 matrix.
I would like to find the last instance of an element in each row of A being greater than the element in the corresponding row of B, and return an n by 1 list of indices.
For example:
A = [1 3 2;
2 5 -1;
0 2 3]
B = [1;
0;
2]
idx = [3;
2;
3]
I'm sure I could do this with a for loop, but would like to avoid it as the matrices are potentially very large.
Many thanks in advance.

답변 (1개)

Geoff Hayes
Geoff Hayes 2015년 2월 13일
Funkadelala - try using the following which assumes that A and B have been defined as above
cell2mat(arrayfun(@(k)find(A(k,:)>B(k),1,'last'),1:size(A,1),'UniformOutput',false)')
We use arrayfun to apply the anonymous function
@(k)find(A(k,:)>B(k),1,'last')
to the kth row of A, using find to find the last index which is greater than the kth element of B. The result from arrayfun is a cell array (row), so we transpose it and convert to a matrix using cell2mat to produce the desired result of
ans =
3
2
3
Try the above and see what happens!
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2015년 2월 21일
funkadelala's answer moved here
Thanks for the response, and sorry for the delay (I've been trying to sort out errors myself).
The above suggestion returns the following error:
Error using cat
Dimensions of matrices being concatenated are not consistent.
Error in cell2mat (line 83)
m{n} = cat(1,c{:,n});
Error in untitled (line 60)
ans = cell2mat(arrayfun(@(k)find(A(k,:)>B(k),1,'last'),1:size(A,1),'UniformOutput',false)');
And simply using:
ans = arrayfun(@(k)find(A(k,:)>B(k,:),1,'last'),A);
Returns the error:
Attempted to access A(-0,:); index must be a positive integer or logical.
Error in @(k)find(A(k,:)>B(k,:),1,'last')
Error in untitled (line 61)
zindex = arrayfun(@(k)find(A(k,:)>B(k,:),1,'last'),A)';
Any ideas?
Geoff Hayes
Geoff Hayes 2015년 2월 21일
funkadelala - are you using a different A and B than the ones described from above, and if so, what are they? Or, what is the output of just
arrayfun(@(k)find(A(k,:)>B(k),1,'last'),1:size(A,1),'UniformOutput',false)

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by