0
votes

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
1
If you are trying to solve the equation you just need T=A\C. Thats your solution. It's called mldivide and does A LOT of things. And remember jut in case: NEVER EVER INVERT A MATRIX - Ander Biguri
Do A(Section1,q) = 1 and same for other three cases and avoid the loop? - Divakar
Ander Biguri : Yes. I will use T=A\C. I just wrote the equation like that in the comment. - Bjartmar
Divakar : I think I can work with A(Section1,q) = 1. - It's just that q, w, e and r aren't just constants. They are calculated for each node. I think I can work something out. Thanks :D - Bjartmar
You don't necessarily want T=A\C. T=pinv(A)*C is probably what you actually want if your system is underdetermined, although it won't work on sparse matrices... - rlbond

1 Answers

2
votes

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

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

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.