필터 지우기
필터 지우기

Iterate through a matrix to find specific entry

조회 수: 7 (최근 30일)
Caitlyn
Caitlyn 2023년 9월 23일
댓글: Stephen23 2023년 9월 23일
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

답변 (1개)

Walter Roberson
Walter Roberson 2023년 9월 23일
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
Dyuman Joshi
Dyuman Joshi 2023년 9월 23일
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 2023년 9월 23일
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.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by