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.

1 visualización (últimos 30 días)
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

Respuesta aceptada

Githin George
Githin George el 6 de Dic. de 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
Elapsed time is 0.701162 seconds.
%% 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
Elapsed time is 17.437640 seconds.
%%
disp("isequal(result_val,result_val1) output: "+ isequal(result_val1,result_val))
isequal(result_val,result_val1) output: true
  2 comentarios
Image Analyst
Image Analyst el 6 de Dic. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Matt J
Matt J el 7 de Dic. de 2024
Editada: Matt J el 7 de Dic. de 2024
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
  2 comentarios
Matt J
Matt J el 7 de Dic. de 2024
Editada: Matt J el 7 de Dic. de 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
Elapsed time is 0.566279 seconds.
%%Using interp1
tic;
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
toc
Elapsed time is 0.017314 seconds.

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by