Vectorization of multiple embedded for loops

1 回表示 (過去 30 日間)
Keith
Keith 2013 年 10 月 24 日
コメント済み: Andrei Bobrov 2013 年 10 月 25 日
I have the following code that includes 3 iterated for loops in order to create an upper diagonal matrix, I plan on performing on large data set many times and want to make as computationally efficient as possible.
data = magic(3);
n = size(data,1);
W = zeros(n,n);
for i = 1:n
for j = i:n
if i==j
www(i,j)=0;
else
for k = 1:n
temp(1,k) = (data(i,k)-data(j,k))^2;
sumTemp = sumTemp + temp(1,k);
end
W(i,j)=sqrt(sumTemp);
end
temp = 0;
sumTemp = 0;
end
end
Answer should look like:
[0 6.4807 9.7980
0 0 6.4807
0 0 0]
I am working it hard right now, but figure I would throw it out there in case anyone has any suggestions that would save me hours of fiddling around. Thanks in advance.
Keith

採用された回答

Andrei Bobrov
Andrei Bobrov 2013 年 10 月 24 日
W = triu(squeeze(sqrt(sum(bsxfun(@minus,data,permute(data,[3 2 1])).^2,2))));
  2 件のコメント
Keith
Keith 2013 年 10 月 24 日
編集済み: Keith 2013 年 10 月 24 日
Andrei - quite impressive. I would like to get to the point where I can vectorize like this. Can you point me to any good learning references. Thanks for quick and accurate response!
Andrei Bobrov
Andrei Bobrov 2013 年 10 月 25 日
Hi Keith! Full vectoring is not always the best solution. About efficient training: I think, this site and documentation for MATLAB.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by