- 0 if any dimension of the array is 0
- max() of the dimensions of the array otherwise
Iterate through a matrix to find specific entry
7 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (1 件)
Walter Roberson
2023 年 9 月 23 日
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
2023 年 9 月 23 日
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 Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!