【问题标题】:Filling known values to sparse Matrix将已知值填充到稀疏矩阵
【发布时间】:2015-02-17 17:26:59
【问题描述】:

我正在尝试使用涉及方程组的 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

【问题讨论】:

  • 如果你想解方程,你只需要T=A\C。那是你的解决方案。它被称为mldivide,做了很多事情。请记住以防万一:永远不要反转矩阵
  • 对其他三种情况执行A(Section1,q) = 1 并避免循环?
  • 安德·比古里:是的。我将使用 T=A\C。我只是在评论中写了这样的方程式。
  • Divakar :我想我可以使用 A(Section1,q) = 1。 - 只是 q、w、e 和 r 不仅仅是常数。它们是针对每个节点计算的。我想我可以解决一些问题。谢谢:D
  • 你不一定想要 T=A\C。如果您的系统不确定,T=pinv(A)*C 可能是您真正想要的,尽管它不适用于稀疏矩阵...

标签: matlab matrix sparse-matrix


【解决方案1】:

您可以构造一个包含行、列和值列表的稀疏矩阵。

例如

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

如果您无法提前构建ijs,您可以使用spalloc 在稀疏矩阵中预先分配空间,这样可以加快分配速度。

【讨论】:

    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2012-07-28
    • 2023-04-05
    • 2023-04-06
    • 2018-01-19
    相关资源
    最近更新 更多