Iterate through a matrix to find specific entry

9 views (last 30 days)
I'm trying to iterate through a matrix to find the entry that is equal to that of another matrix using nested for loops only - NOT the find function. Here is what I have:
*Z = value of matrix at specific entry
My2ndFunc = function that creates another matrix
for i = 1:length(a)
for j = 1:length(a)
if Z == My2ndFunc(2,-3.6)
fprintf('The entry is%g \n', a(i,j))
end
end
end

Answers (1)

Walter Roberson
Walter Roberson on 23 Sep 2023
Reminder: length is defined as:
  • 0 if any dimension of the array is 0
  • max() of the dimensions of the array otherwise
You appear to be searching a 2D array, and it is not certain that it will have the same number of rows and columns, so your i and j should probably not be looping 1:length(a)
You are not assigning any value to Z.
You are looping over i and j but you do not use i and j except to display an output. But because you are not changing Z, you are performing exactly the same test for all iterations, so either you will get no values displayed or else you will get them all displayed.
It is inefficient to re-calculate My2ndFunc(2,-3.6) for every iteration. It would be better to calculate it only once.
Remember that == is bit-for-bit equality. If two numbers differ by one part in a quadrillion, MATLAB will not consider them to be equal. If you calculate the same value by two different methods that are algebraically the same, the two calculated values will not necessarily be the same. 0.1 + 0.2 - 0.3 is not the same as 0.2 - 0.3 + 0.1
  3 Comments
Dyuman Joshi
Dyuman Joshi on 23 Sep 2023
Why not use find?
Also, size(), by default, returns a 2 element vector. And when you use colon, : for a nonscalar array, only the first values of the arrays are used.
Use size(a,1) for number of rows and size(a,2) for number of columns. Loook into the documentation of size for more info.
Stephen23
Stephen23 on 23 Sep 2023
On this line:
if Z == Q
you should compare the absolute difference against a tolerance, for the reason that Walter Roberson already explained in their last paragraph.
Note that you do not change anything inside the loop, so they appear to be completely superfluous.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!