MATLAB Answers

# logical indexing on a matrix

2 views (last 30 days)
MatG on 8 Sep 2020
Answered: Walter Roberson on 8 Sep 2020
Is there a brief way without using much loops to take "all of certain columns" of a matrix and evaluate whether they're larger than the first column of that marrix?
nSize = 10;
mymatrix = rand(nSize,5);
IndexToCompare = logical(round(mymatrix));
myBenchmark = mymatrix(:,1);
% A. I want to replace the following loop with some statement such as B which uses logical indexing but for a matrix rather than a vector
for i=1:nSize
result(i) = sum(mymatrix(IndexToCompare(i,:)) > myBenchmark(i,1));
end
%B. this is going to throw error due to size mismatch.
result = sum(mymatrix(IndexToCompare) > myBenchmark);
##### 1 CommentShowHide None
madhan ravi on 8 Sep 2020
Do you even realise the loop and the last line have two different in depth details? And that’s one of the reasons to give you a straight answer?

Sign in to comment.

### Answers (1)

Walter Roberson on 8 Sep 2020
all(mymatrix(IndexToCompare, :) > myBenchmark,1)
The result would be a vector of the same length as IndexToCompare, and which will be true for the columns corresponding to IndexToCompare in which each row entry is strictly greater than the corresponding entry in myBenchmark .
Note that the random generation you are doing can include the first column, and the first column can never be strictly greater than itself.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!