Reputation: 906
Currently, I need to develop an algorithm to solve the Optimization Problem
I encounter a problem about my way to calculate the distance between facility is not efficient enough.
Now, I given the matrices, which is the length of facilities.
A = [0.0300 % The left most facility
0.0400 % 2nd
0.0500 % 3rd
0.0200 % 4th
0.0600]; % The right most facility
Say, I want to find the distance between the center of two facilities.(Assume no gap between) For example:
Distance between center of 2nd and 5th facility = 0.0400/2 + 0.0500 + 0.0200 + 0.0600/2 = 0.1200
From that, we can form a matrix B which is the output I want (can be symmetrical matrix also)
B = [0 0.0350 0.0800 0.1150 0.1550
0 0 0.0450 0.0800 0.1200
0 0 0 0.0350 0.0750
0 0 0 0 0.0400
0 0 0 0 0];
I was try to avoid nested for loop. This is the best that I can think off in order the get matrix B.
n = numel(A);
x = triu(repmat(A,1,n));
B = zeros(5);
x = x - diag(diag(x)/2);
for i=1:4
x(i,:) = x(i,:)/2;
y = x;
B(i,:) = sum(y);
x(i,:) = 0;
end
B = B - diag(diag(B))
Of course, the matrix size very large in reality and my way is not efficient enough. Is there any trick to get the matrix B instead of using for loop?
Upvotes: 0
Views: 57
Reputation: 4768
You could think about the problem in a different way - essentially what you're calculating is the average of the distance between the start points of each facility and the end points of each facility. i.e.
<------start dist------>
[ A ][ B ][ C ][ D ]
<--------------end dist-------------->
You can calculate the start and end points of each facility using:
end_pts = cumsum(A);
start_pts = end_pts - A;
You can then calculate the start and end distances using:
start_dist = abs(bsxfun(@minus,start_pts,start_pts'));
end_dist = abs(bsxfun(@minus,end_pts,end_pts'));
You then take the average of these matrices to find the distance between the centres:
B = (start_dist + end_dist)./2;
Upvotes: 1