Nested for loop vectorization

조회 수: 6 (최근 30일)
Gabriele Dessena
Gabriele Dessena 2021년 4월 1일
편집: Gabriele Dessena 2021년 4월 1일
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);

채택된 답변

Marco Riani
Marco Riani 2021년 4월 1일
% 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
Gabriele Dessena
Gabriele Dessena 2021년 4월 1일
편집: Gabriele Dessena 2021년 4월 1일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by