Comparing matrices of different length
5 views (last 30 days)
Show older comments
I have two matrices of different length. For both matrices the first column is x-coordinate, second column is y-coordinate and third column is height. I would like to compare all points for both matrices and for those points where the distance is less than 100 it should calculate the height difference. Is there a smart way of doing this?
3 Comments
KSSV
on 28 Apr 2017
Question need to be more clear. Let A and B be the set of points; pick one point from A..say A(i,:), you want to pick all the points in B which are less then 100 units of distance from Ai..and like for each and very point for A?
Answers (2)
Stephen23
on 28 Apr 2017
Edited: Stephen23
on 28 Apr 2017
If the matrices are not large then you can easily use permute and bsxfun. Here I put the A points down the first dimension, and the B points along the second dimension of the output matrices.
>> A = [0,0,1;10,10,0]; % [X,Y,H]
>> B = [1,1,0;11,11,2;111,111,3]; % [X,Y,H]
>> A3 = permute(A,[1,3,2]);
>> B3 = permute(B,[3,1,2]);
>> H = bsxfun(@minus,A3(:,:,3),B3(:,:,3)); % all height differences
Actually all height differences are in H. If you want to identify the distances between the points, then do this:
>> M = bsxfun(@minus,A3(:,:,1:2),B3(:,:,1:2)); % all X & Y differences
>> D = sqrt(sum(M.^2,3)) % euclidean distance from X & Y differences
D =
1.4142 15.5563 156.9777
12.7279 1.4142 142.8356
>> H(D>=100) = NaN % optional
H =
1 -1 NaN
0 -2 NaN
Stephen23
on 28 Apr 2017
Edited: Stephen23
on 28 Apr 2017
For large matrices you could (possibly) speed up your code by only using one loop, and vectorizing the operations in the inner loop:
A = randi(10000,450000,3);
B = randi(10000,650000,3);
C = {};
for k = 1:size(A,1)
D = sqrt(...
(B(:,1)-A(k,1)).^2 + ...
(B(:,2)-A(k,2)).^2);
idx = D<100;
C{end+1} = B(idx,3)-A(k,3);
end
2 Comments
Stephen23
on 28 Apr 2017
Edited: Stephen23
on 28 Apr 2017
If memory was not limited, then the fully vectorized approach would be exactly as I showed in my other answer, using bsxfun. The reason to use one loop is simply because (most likely) you are using a PC and have some GB of memory. Using one loop means that the intermediate arrays are of a size that can actually be stored in memory.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!