MATLAB Answers

HA
0

How to find the closest value to a constant in a 2D matrix

Asked by HA
on 5 Feb 2019
Latest activity Commented on by HA
on 5 Feb 2019
Hello,
I have a 2D matrix of random numbers and NaNs, of 15x129. I want to find where in the matrix the values are closest to the number 15 along each column, and output a logical 15x129 matrix (where number is closest to 15 = 1, where number is less than 15 = 0 or nan) . So out of the 15 values, which value is closest to the number 15.
Thank you,
Holly

1 Answer

Answer by YT
on 5 Feb 2019
 Accepted Answer

Probably something like this
A = rand([15 129])*100; %matrix with random values
[~,I] = min(abs(A - 15),[],1); %get indices for values closest to 15
logicalMat = false(size(A)); %preallocate logical matrix
arrayLength = size(A,2);
for jj = 1:arrayLength
logicalMat(I(jj),jj) = 1; %fill logical matrix
end

  1 Comment

This works great, thank you!

Sign in to comment.