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

1 view (last 30 days)
Attempts so far.
for inputMat = [c];
[row,col] = find (c==700);
end
inputMat = [c];
[myRow, myCol] = find(inputMat (closest(700)));
numericalAns = [myRow myCol];

Accepted Answer

John D'Errico
John D'Errico on 20 Apr 2021
Edited: John D'Errico on 20 Apr 2021
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

More Answers (1)

Jan
Jan on 20 Apr 2021
Edited: Jan on 21 Apr 2021
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 Comments
Alex Hinchcliffe
Alex Hinchcliffe on 20 Apr 2021
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.

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!