Reputation: 509
Given a matrix A
in matlab with:
3 1
4 5
7 8
and another matrix B
which could be referred to as some reference points (each row is reference point that is to be compared to each row of A
),
1 1
1 2
I need to compute a matrix C
, such that
4 5
25 18
85 72
Where each row of C
is the difference (squared L2 norm) between each row of A
and the rows of B
. One possible way to do this in MATLAB is to first create a zero matrix C
, C = zeros(5,2)
, and then use double for-loops to fill in the appropriate value. Is there any other efficient/simpler way in MATLAB?
Find the code snippet below
C = zeros(5,2)
for i = 1:rows
for j = 1:rows2
C(i,j) = (norm(A(i,:)-B(j,:)))^2
end
end
Upvotes: 2
Views: 266
Reputation: 101024
Maybe you can try bsxfun
like below
A = [3,1; 4,5;7,8];
B = [1,1;1,2];
% you can first rewrite A and B in complex coordinates to simplify the computation, and then compute difference of two complex values
C = abs(bsxfun(@minus,A*[1;1j],transpose(B*[1;1j]))).^2;
and you will get
C =
4.0000 5.0000
25.0000 18.0000
85.0000 72.0000
Upvotes: 2
Reputation: 60444
A solution similar to ThomasIsCoding's, but generalized to any number of dimensions (=columns). Thomas' answer requires A
and B
to have exactly 2 columns to use the complex representation. Here, we use a 3rd array dimension instead of complex values:
n = 3; % number of spatial dimensions for computing the L2 norm
A = 10*rand(20,n);
B = 10*rand(4,n);
C = sum((reshape(A,[],1,n) - reshape(B,1,[],n)).^2,3)
First we reshape A
, such that its rows remain rows, but its columns are arranged along the 3rd array dimension. We reshape B
similarly, but its rows become columns, and its columns are moved to the 3rd dimension. This arrangement of the first two dimensions match that of the output C
.
Next we take the difference (using implicit singleton expansion, for older versions of MATLAB you'd need to use bsxfun
), square, and sum along the 3rd dimension.
Upvotes: 3