Question related to vectorized matrix operation.

i have two matrices A and B; A is say (Nx3) where N is rather large like 1000+... B is (nx2) where n is rather smaller of the order 10 or so.. but it does not matter it is smaller than A row size. i would like to compute
for i = 1:N
D = ( A(i,1)- B(1:n,1) )^2 + (A(i,2) - B(1:n,2)^2 )
end
for e.g. if N is 4, and n =2 then D = a [4x2] matrix...
I am able to perform this using for loops without much difficulty but would like to try using the vectorized Matrix operations instead for improving the performance and speed. Thanks in advance.

 採用された回答

Stephen23
Stephen23 2017 年 1 月 22 日
編集済み: Andrei Bobrov 2017 年 1 月 23 日

0 投票

>> A = randi(9,4,3)
A =
4 2 9
9 4 4
5 4 8
4 2 8
>> B = randi(9,3,2)
B =
3 2
6 4
3 1
>> D = bsxfun(@minus,A(:,1),B(:,1).').^2 + bsxfun(@minus,A(:,2),B(:,2).').^2
D =
1 8 2
40 9 45
8 1 13
1 8 2

4 件のコメント

Pappu Murthy
Pappu Murthy 2017 年 1 月 23 日
編集済み: Stephen23 2017 年 1 月 23 日
I am not able to follow your solution since I am not very familiar with the function bsxfun that you used. however, I can see the answer is wrong. Here is my long notation code:
for i =1:4
Dist = ((A(i,1)-B(:,1)).^2 + (A(i,2)-B(:,2)).^2)'
C(i,:)=Dist;
end
C =
1 8 2
40 9 45
8 1 13
1 8 2
Which is quite different from your solution. Could you look over and see if you can fix it, since your way if works is a lot more elegant than my for loop way. Thanks.
Andrei Bobrov
Andrei Bobrov 2017 年 1 月 23 日
I'm corrected Stephen's answer
Stephen23
Stephen23 2017 年 1 月 23 日
Thank you Andrei Bobrov.
Pappu Murthy
Pappu Murthy 2017 年 1 月 23 日
thanks to both of you after the corrections I am able to get the right answer and I found this answer to be the most direct and also verified that many times faster than my answer for large size matrices. Thanks again. I will now go ahead and accept the answer.

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2017 年 1 月 23 日
編集済み: Andrei Bobrov 2017 年 1 月 23 日

1 投票

My variants:
For R2016b and later
>> C2 = squeeze(sum((A(:,1:2) - permute(B,[3,2,1])).^2,2))
C2 =
1 8 2
40 9 45
8 1 13
1 8 2
and with bsxfun:
>> C3 = squeeze(sum(bsxfun(@minus,A(:,1:2),permute(B,[3,2,1])).^2,2))
C3 =
1 8 2
40 9 45
8 1 13
1 8 2

1 件のコメント

Pappu Murthy
Pappu Murthy 2017 年 1 月 23 日
編集済み: Pappu Murthy 2017 年 1 月 23 日
The first solution did not work in 2016a but worked ok in 2016b. Thanks for suggesting the alternative answers, although After testing a lot the original solution and your interpretation with bsxfun appear to be the best from speed point of view. Your first approach was a bit slower. I have tried on huge matrices to establish the speed correctly.

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

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

質問済み:

2017 年 1 月 22 日

編集済み:

2017 年 1 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by