Fastest way to find the values and indices of the entries of a vector X that are closest to each entry of a matrix A.
2 views (last 30 days)
Show older comments
Basically wondering if there is a faster way to do something like this:
X = [0:.05:1]; % the vector
A = rand(100); % the matrix
result_val = zeros(100);
result_idx = zeros(100);
for i = 1:100
for j = 1:100
[result_val(i,j), result_idx(i,j)] = min( abs(A(i,j) - X) );
end
end
0 Comments
Accepted Answer
Githin George
on 6 Dec 2024
You can vectorize the operation as shown below:
X = 0:0.05:1; % the vector
A = rand(5000); % the matrix
%% Vectorized Approach
tic
% Reshape X to create 1x1xsize(X) array
X = reshape(X, 1, 1, []);
% Calculate the absolute differences NxNxsize(X)
differences = abs(A - X);
% Find the minimum differences and their indices along dim=3
[result_val, result_idx] = min(differences, [], 3);
toc
%% Non Vectorized Approach
tic
result_val1 = zeros(5000);
result_idx1 = zeros(5000);
for i = 1:5000
for j = 1:5000
[result_val1(i,j), result_idx1(i,j)] = min( abs(A(i,j) - X) );
end
end
toc
%%
disp("isequal(result_val,result_val1) output: "+ isequal(result_val1,result_val))
2 Comments
Image Analyst
on 6 Dec 2024
If you want to wait for additional answers using different approaches, you can.
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.
For full details on how to earn reputation points see: https://www.mathworks.com/matlabcentral/answers/help?s_tid=al_priv#reputation
More Answers (1)
Matt J
on 7 Dec 2024
Edited: Matt J
on 7 Dec 2024
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
2 Comments
Matt J
on 7 Dec 2024
Edited: Matt J
on 7 Dec 2024
Speed comparison:
X = linspace(0,1,500); % the vector
A = rand(1000); % the matrix
%%Using min
tic
% Calculate the absolute differences NxNxsize(X)
differences = abs(A - reshape(X, 1, 1, []));
% Find the minimum differences and their indices along dim=3
[result_val, result_idx] = min(differences, [], 3);
toc
%%Using interp1
tic;
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
toc
See Also
Categories
Find more on Manage Products in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!