MATLAB Answers

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

6 views (last 30 days)
funkadelala on 13 Feb 2015
Commented: Geoff Hayes on 21 Feb 2015
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;
idx = [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.

Answers (1)

Geoff Hayes
Geoff Hayes on 13 Feb 2015
Funkadelala - try using the following which assumes that A and B have been defined as above
We use arrayfun to apply the anonymous function
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 =
Try the above and see what happens!
Geoff Hayes
Geoff Hayes on 21 Feb 2015
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

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!