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개)

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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by