Nested for loop vectorization

6 Ansichten (letzte 30 Tage)
Gabriele Dessena
Gabriele Dessena am 1 Apr. 2021
Bearbeitet: Gabriele Dessena am 1 Apr. 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);

Akzeptierte Antwort

Marco Riani
Marco Riani am 1 Apr. 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 Kommentar
Gabriele Dessena
Gabriele Dessena am 1 Apr. 2021
Bearbeitet: Gabriele Dessena am 1 Apr. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by