Nested for loop vectorization

2 views (last 30 days)
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);

Accepted Answer

Marco Riani
Marco Riani on 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 Comment
Gabriele Dessena
Gabriele Dessena on 1 Apr 2021
Edited: Gabriele Dessena on 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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!