向量中元素的总和,以获得对应的矩阵 [英] Sum of element in Vector to get the correspond Matrix

查看:109
本文介绍了向量中元素的总和,以获得对应的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我需要开发一种算法来解决优化问题

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:

第二和第五设施中心之间的距离= 0.0400/2 + 0.0500 + 0.0200 + 0.0600/2 = 0.1200

Distance between center of 2nd and 5th facility = 0.0400/2 + 0.0500 + 0.0200 + 0.0600/2 = 0.1200

由此,我们可以形成矩阵B,这是我想要的输出(也可以是对称矩阵)

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];

我试图避免嵌套for循环.这是我可以考虑的最好方法,用于获取矩阵B.

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))

当然,现实中矩阵的大小非常大,我的方法效率还不够.是否有任何技巧可以获取矩阵B而不是使用for循环?

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?

推荐答案

您可以以不同的方式考虑问题-本质上,您要计算的是每个设施起点和终点之间的平均距离每个设施的分数.即

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;

这篇关于向量中元素的总和,以获得对应的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆