I need to calculate the distance matrix between these locations in ev charging stations placement

조회 수: 1 (최근 30일)
I'm working on an EV charging station project and have coordinates of potential station locations. I need to calculate the distance matrix between these locations using MATLAB. How can I efficiently compute this matrix based on the coordinates provided

채택된 답변

recent works
recent works 2023년 11월 30일
% Assuming chargingStationCoordinates contains the coordinates of potential charging stations
% Calculate distance matrix between charging stations
numStations = size(chargingStationCoordinates, 1);
distanceMatrix = zeros(numStations);
for i = 1:numStations
for j = 1:numStations
distanceMatrix(i, j) = norm(chargingStationCoordinates(i, :) - chargingStationCoordinates(j, :));
end
end
disp('Distance Matrix:');
disp(distanceMatrix);

추가 답변 (1개)

Konrad
Konrad 2023년 11월 30일
Hi,
let's say you have 10 2d coordinates of charging stations
pos = rand(10,2);
Then one efficient way of computing the distance matrix would be:
m = pos * pos';
dist = sqrt(bsxfun(@plus, diag(m), diag(m)') - 2*m);
  댓글 수: 1
Konrad
Konrad 2023년 11월 30일
편집: Konrad 2023년 11월 30일
Note that since 2016 or so, Matlab does implicit singleton expansion, i.e. you don't need the bsxfun() but you can write:
%sqrt(diag(m) + diag(m)' - 2*m)
which seems to be considerably faster.
EDIT: After some more testing it's not much of a difference:
tic;
for k = 1:1000
pos = rand(200,2);
m = pos * pos';
dist = sqrt(diag(m)+diag(m)' - 2*m);
end
toc
Elapsed time is 0.130854 seconds.
tic;
for k = 1:1000
pos = rand(200,2);
m = pos * pos';
dist = sqrt(bsxfun(@plus, diag(m), diag(m)') - 2*m);
end
toc
Elapsed time is 0.148703 seconds.
A different approach using the Pythagorean theorem:
tic;
for k = 1:1000
pos = rand(200,2);
dist = sqrt(sum( (permute(pos,[1 3 2])-permute(pos,[3 1 2])).^2 ,3));
end
toc
Elapsed time is 0.166725 seconds.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by