[英]Filling known values to sparse Matrix
我正在尝试使用涉及方程系统的FDE(有限差分法)解决Matlab中的问题。
所以我有
[A] {T} = {C}-> [A] ^(-1){C} = {T}
我“知道” [A]和{C}的所有值。 由于矩阵大部分为零,因此我使用的是稀疏矩阵。
但是Matlab在向矩阵填充已知值时会警告我。
该稀疏索引表达可能很慢。
这是一个例子:
clear;clc;
% Number of nodes.
nodes = 5000;
% My
A = sparse(nodes,nodes); % Known parameters.
C = sparse(nodes,1); % Known parameters.
T = sparse(nodes,1); % Trying to find.
% Solving equation: [A]{T}={C} -> [A]^(-1){C}={T}
% I'm trying to fill my known values to [A]
% I have 40+ 'sections' with different values. For this example I use one
% section with all values equals to 1.
Section1 = [1, 30, 50, 60, 100, 430, 4500]; % Nodes in section 1.
% Random numbers for the example. (I generate them for each node.)
q = 10;
w = 400;
e = 1000;
r = 3500;
for i = 1:nodes
if any(Section1(:)==i)
A(i,q) = 1; % Error on this line
A(i,w) = 1; % Error on this line
A(i,e) = 1; % Error on this line
A(i,r) = 1; % Error on this line
end
end
您可以使用行,列和值的列表构造稀疏矩阵。
例如
>> i = [1,2,3];
>> j = [2,3,4];
>> s = [10, 20, 30];
>> A = sparse(i,j,s,5,5)
A =
(1,2) 10
(2,3) 20
(3,4) 30
>> full(A)
ans =
0 10 0 0 0
0 0 20 0 0
0 0 0 30 0
0 0 0 0 0
0 0 0 0 0
如果无法提前生成i
, j
和s
,则可以使用spalloc
在稀疏矩阵中预分配空间,这将加快分配速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.