简体   繁体   中英

Filling known values to sparse Matrix

I'm trying to solve a problem in Matlab using FDE (Finite Difference method) which involves system of equations.

So I have

[A]{T}={C} -> [A]^(-1){C}={T}

I "know" all the values for [A] and {C}. As the matrix is mostly zeros I'm using sparse matrix.

But Matlab is giving me a warning while filling known values to the matrix.

This sparse indexing expression is likely to be slow.

Here is an example:

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

You can construct a sparse matrix with lists of row, column, and values.

EG

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

If you can't build i , j , and s ahead of time, you can use use spalloc to pre-allocate space in your sparse matrix, which should speed up assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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