How to find the row and column for a value within a matrix [c] nearest or equal to 700.

1 回表示 (過去 30 日間)
Attempts so far.
for inputMat = [c];
[row,col] = find (c==700);
end
inputMat = [c];
[myRow, myCol] = find(inputMat (closest(700)));
numericalAns = [myRow myCol];

採用された回答

John D'Errico
John D'Errico 2021 年 4 月 20 日
編集済み: John D'Errico 2021 年 4 月 20 日
Easy. And there would be many ways to do it.
c = rand(5,5)*1000
c = 5×5
954.2387 395.1216 623.5493 716.9854 244.7619 872.3532 774.9458 535.5974 226.3258 561.0368 336.4275 785.2196 738.6107 98.0277 66.3741 403.5059 623.4173 598.7175 232.5904 992.2769 692.0418 126.7045 426.2907 594.1339 735.1474
[~,ind] = min(abs(c(:) - 700))
ind = 5
[rowind,colind] = ind2sub(size(c),ind)
rowind = 5
colind = 1
So the closest element to 700 lives in row 5, column 1.
c(rowind,colind)
ans = 692.0418
  1 件のコメント
Alex Hinchcliffe
Alex Hinchcliffe 2021 年 4 月 20 日
Thanks John, nice example and explanation. This seems to work very well.

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2021 年 4 月 20 日
編集済み: Jan 2021 年 4 月 21 日
find(inputMat (closest(700)))
This is pure guessing. Notice that a command like closest(X) cannot even work in theory, because you provide one input only. So if this command exists, Matlab would ask: "closest to what?"
for inputMat = [c];
This is not the way Matlab's FOR loop works.
Guessing is no successful strategy for such a powerful tool as Matlab. Please read the GEtting Started chapters of the documentation and read Matlab's Onramp: https://www.mathworks.com/learn/tutorials/matlab-onramp.html
[value, index] = min(abs(c(:) - 700))
[row, col] = find(c == c(index)) % [EDITED, Typo fixed]
% Replies multiple matchs, if there are some
  2 件のコメント
Alex Hinchcliffe
Alex Hinchcliffe 2021 年 4 月 20 日
Thanks for the reply, i couldnt seem to get a row and col value with this though. It came up with
row =
0×1 empty double column vector
col =
0×1 empty double column vector
I will have a read through the information in the link.
Jan
Jan 2021 年 4 月 21 日
Yes, the code failed due to a typo. This is fixed now.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by