matlab中diag w k,在MATLAB中构造邻接矩阵

如果您注意到,您正在创建的邻接矩阵有一个独特的模式。具体来说,它们是对称的和带状的。您可以利用这个事实使用diag函数轻松创建矩阵(如果您想制作稀疏矩阵,则可以使用spdiags函数)。以下是使用上面的示例矩阵作为示例为每种情况创建邻接矩阵的方法:

4个连接的邻居:

mat = [1 2 3; 4 5 6; 7 8 9]; % Sample matrix

[r, c] = size(mat); % Get the matrix size

diagVec1 = repmat([ones(c-1, 1); 0], r, 1); % Make the first diagonal vector

% (for horizontal connections)

diagVec1 = diagVec1(1:end-1); % Remove the last value

diagVec2 = ones(c*(r-1), 1); % Make the second diagonal vector

% (for vertical connections)

adj = diag(diagVec1, 1)+diag(diagVec2, c); % Add the diagonals to a zero matrix

adj = adj+adj.'; % Add the matrix to a transposed copy of

% itself to make it symmetric

你会得到以下矩阵:

adj =

0 1 0 1 0 0 0 0 0

1 0 1 0 1 0 0 0 0

0 1 0 0 0 1 0 0 0

1 0 0 0 1 0 1 0 0

0 1 0 1 0 1 0 1 0

0 0 1 0 1 0 0 0 1

0 0 0 1 0 0 0 1 0

0 0 0 0 1 0 1 0 1

0 0 0 0 0 1 0 1 0

8个连接的邻居:

mat = [1 2 3; 4 5 6; 7 8 9]; % Sample matrix

[r, c] = size(mat); % Get the matrix size

diagVec1 = repmat([ones(c-1, 1); 0], r, 1); % Make the first diagonal vector

% (for horizontal connections)

diagVec1 = diagVec1(1:end-1); % Remove the last value

diagVec2 = [0; diagVec1(1:(c*(r-1)))]; % Make the second diagonal vector

% (for anti-diagonal connections)

diagVec3 = ones(c*(r-1), 1); % Make the third diagonal vector

% (for vertical connections)

diagVec4 = diagVec2(2:end-1); % Make the fourth diagonal vector

% (for diagonal connections)

adj = diag(diagVec1, 1)+... % Add the diagonals to a zero matrix

diag(diagVec2, c-1)+...

diag(diagVec3, c)+...

diag(diagVec4, c+1);

adj = adj+adj.'; % Add the matrix to a transposed copy of

% itself to make it symmetric

你会得到以下矩阵:

adj =

0 1 0 1 1 0 0 0 0

1 0 1 1 1 1 0 0 0

0 1 0 0 1 1 0 0 0

1 1 0 0 1 0 1 1 0

1 1 1 1 0 1 1 1 1

0 1 1 0 1 0 0 1 1

0 0 0 1 1 0 0 1 0

0 0 0 1 1 1 1 0 1

0 0 0 0 1 1 0 1 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值