简体   繁体   English

MATLAB:从矩阵中找到每个节点的唯一后继对象的数量

[英]MATLAB: Finding the number of unique successors of each node from a matrix

I'm new to the MATLAB software and am currently trying to learn it without being formally taught and have a pretty simple question. 我是MATLAB软件的新手,目前正尝试在没有经过正式授课的情况下学习它,并且有一个非常简单的问题。

I have an adjacency matrix that corresponds to a digraph and want to see what nodes are connected by a walk to other nodes in the network. 我有一个与有向图相对应的邻接矩阵,并想查看通过步行将哪些节点连接到网络中的其他节点。 So, given an adjacency matrix with n nodes: 因此,给定一个具有n个节点的邻接矩阵:

D = [0,1,1,0,0,0,0;
     0,0,0,1,1,0,0;
     0,0,0,0,1,0,0;
     0,0,0,0,0,1,0;
     0,0,0,0,0,1,0;
     0,0,0,0,0,0,1;
     0,0,0,0,0,0,0]

I want to find the number of unique successors for each node. 我想找到每个节点的唯一后继数量。 I am currently using a code to do this, but it is very clunky; 我目前正在使用代码来执行此操作,但是它很笨重; every time I change the matrix I need to change the code. 每次更改矩阵时,都需要更改代码。 It is as follows: 如下:

D1 = logical(D^1 + D^2 + D^3 + D^4 + D^5 + D^6 + D^7);

D1(logical(eye(size(D1)))) = 0;

B = sum(transpose(D1));

Is there any way to tidy up the code and just make a more general one!? 有什么方法可以整理代码并编写更通用的代码!?

You can change D^1 + D^2 + D^3 + D^4 + D^5 + D^6 + D^7 with D*(D^size(D,1)-eye(size(D)))/(D-eye(size(D))) and use .*~eye(size(D)) to get rid of the diagonal and end up with 您可以使用D*(D^size(D,1)-eye(size(D)))/(D-eye(size(D)))更改D^1 + D^2 + D^3 + D^4 + D^5 + D^6 + D^7 D*(D^size(D,1)-eye(size(D)))/(D-eye(size(D)))并使用.*~eye(size(D))摆脱对角线并最终得到

B=sum(logical(D*(D^size(D,1)-eye(size(D)))/(D-eye(size(D)))).*~eye(size(D)), 2)';

However, I personally prefer your code. 但是,我个人更喜欢您的代码。 It is easier to understand what it is doing. 更容易了解它在做什么。

You can change 你可以改变

D1 = logical(D^1 + D^2 + D^3 + D^4 + D^5 + D^6 + D^7);

to

aux = (arrayfun(@(x) D^x, 1:length(D), 'UniformOutput',false));
D1 = any(cat(3,aux{:}),3);

which is valid for all sizes of D . 对于所有大小的D都有效。

Here is a straightforward way: 这是一个简单的方法:

N = length(D);
DD = zeros(N);
for i=1:N
    DD = DD + D^i;
end
DD = logical(DD);
DD(1:N+1:end) = false;
B = sum(DD,2);

Perhaps a link to explain the meaning of the powers of the adjacency matrix . 也许是一个解释邻接矩阵幂的含义的链接。


You can use the following code to visualize the resulting graph (note that the plot doesn't distinguish directed/undirected edges): 您可以使用以下代码来可视化生成的图形(请注意,该图不区分有向/无向边):

% circular layout
t = linspace(0,2*pi,N+1)'; t(end) = [];
xy = [cos(t) sin(t)];

% plot graph and label nodes
subplot(121), gplot(DD, xy, '-*')
text(xy(:,1), xy(:,2), num2str((1:N)'), 'BackgroundColor',[.4 .9 .5], ...
    'VerticalAlign','bottom', 'HorizontalAlign','right')
axis square off

% adjacency matrix
subplot(122), spy(DD)
set(gca, 'XTick',1:N, 'YTick',1:N)
ylabel('from'), xlabel('to')

图形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM