Nested for loop vectorization

2 visualizaciones (últimos 30 días)
Gabriele Dessena
Gabriele Dessena el 1 de Abr. de 2021
Editada: Gabriele Dessena el 1 de Abr. de 2021
Hello everyone,
I am trying to vectorize the creation of this symmetric matrix.
I have tried with meshgrid and ngrid, but I could not find a way to make them work with the way I use X.
Any advice?
Thank you!
X = [1:10; 2:11]';
n = length(X);
theta = .1;
Mat = zeros(n,n);
for i=1:n
for j=i+1:n
Mat(i,j)=exp(-sum(theta.*abs(X(i,:)-X(j,:)).^p));
end
end
Mat = Mat+Mat'+eye(n);

Respuesta aceptada

Marco Riani
Marco Riani el 1 de Abr. de 2021
% Hi, in your code p is not defined. I assume it is a scalar
% If you want to avoid the loop the answer is
% Mat=exp(-theta*(squareform(pdist(X,'minkowski',p))).^p);
% The code below checks that my implementation gives the same answer as
% your implementation
% Best
% Marco
X = [1:10; 2:11]';
p=3;
n = length(X);
theta = 0.1;
Mat = zeros(n,n);
for i=1:n
for j=i+1:n
Mat(i,j)=exp(-sum(theta.*abs(X(i,:)-X(j,:)).^p));
end
end
Mat = Mat+Mat'+eye(n);
Matchk=exp(-theta*(squareform(pdist(X,'minkowski',p))).^p);
disp(max(abs(Mat-Matchk),[],'all'))
  1 comentario
Gabriele Dessena
Gabriele Dessena el 1 de Abr. de 2021
Editada: Gabriele Dessena el 1 de Abr. de 2021
It works flawlessly, just a note on performance for future readers. The code is more efficient than the nested loop for n>100.
Grazie Mille Marco

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by