Convert for loop to vector multiplication.

1 回表示 (過去 30 日間)
hello_world
hello_world 2016 年 8 月 17 日
編集済み: hello_world 2016 年 8 月 17 日
Hello Friends,
I have the following:
A = [1 2 3;
4 5 6;
7 8 9];
B = [10 11 12;
13 14 15];
[N1, D1] = size(A);
[N2, D2] = size(B);
for i = 1:N2
diffs = bsxfun(@minus, A, B(i, :));
dists(:, i) = sqrt(sum(diffs.^2, 2));
end
How can I replace the 2nd line in for loop in order to write it in a vector form? I have tried something like this:
for i = 1:N2
diffs = bsxfun(@minus, A, B(i, :));
dists = sqrt(diffs.*diffs);
end
But the two results are different. I am trying to achieve the following:
distance = sqrt((A-B).*(A-B))
which should be the Euclidean distance. I want to keep it as presented above without changing format to compute distance or using repmat, etc.

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 8 月 17 日
dists = sqrt(diffs.*diffs);
is not going to be doing any sum. You might be thinking of the * operator instead of the .* operator.
You could also look at dot() and norm()
  1 件のコメント
hello_world
hello_world 2016 年 8 月 17 日
編集済み: hello_world 2016 年 8 月 17 日
Can you elaborate please with a work example using * so that the two results be the same.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by