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 Center および File ExchangeCreating 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