我正在尝试使用涉及方程组的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
答案 0 :(得分:2)
您可以使用行,列和值列表构建稀疏矩阵。
E.G。
>> 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
来预先分配稀疏空间矩阵,这应该加快分配。