Searching through a matrix to find a specific element

9 views (last 30 days)
I have a 12 x 12 matrix and I am asked to search for a specific element (variable such as x) using logical matrices and the find function. How can I approach this?
  2 Comments
Cris LaPierre
Cris LaPierre on 21 Mar 2021
Edited: Cris LaPierre on 21 Mar 2021
Based on what you've shared, I'd suggest learning about logical arrays (Ch 11 of MATLAB Onramp) and the find function's documentation page.
Consider sharing your matrix so that we know what it is we are working with.
NotRiyad NotHosein
NotRiyad NotHosein on 21 Mar 2021
It is a random 12x12 matrix of integers and I have been asked to find a random element such as 5 or 10. Will check your link as well.

Sign in to comment.

Answers (1)

DGM
DGM on 21 Mar 2021
Let's start with a constant array so we know what to expect:
A=[94 40 91 47 57; ...
47 5 59 64 75; ...
93 38 95 5 46; ...
36 39 69 48 25; ...
44 92 70 10 49];
We can generate a logical map the same size as A using any logical test we want:
logicalmap=(A==5);
% this operation yields a logical array
% [false false false false false; ...
% false true false false false; ...
% false false false true false; ...
% false false false false false; ...
% false false false false false]
If we only want a list of the matching elements, we can use find():
matchindex=find(logicalmap);
% this operation yields a vector of the linear indices
% wherein LOGICALMAP is true (i.e. [7; 18])
Either one can be used to extract the array elements of interest:
A(logicalmap)
A(matchindex)
% both return the column vector [5; 5]
If subscripts are required instead of linear indices, you can convert them using ind2sub()

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

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

Start Hunting!