PCG on a large sparse matrix from Finite difference method

16 views (last 30 days)
Liam Lau
Liam Lau on 28 Jun 2018
Answered: Josh Meyer on 23 Sep 2019
I have to solve a generic matrix equation A*x=b, but A is large so I was planning to do it iteratively, or by using the PCG function in matlab. Is there any way to write the matrix parametrically in a separate function so that it doesn't have to be stored in memory? I read the documentation for PCG, but I didn't quite understand the section of using a function instead of matrix A for a large matrix.

Answers (1)

Josh Meyer
Josh Meyer on 23 Sep 2019
Yes, you can provide the coefficient matrix as a function handle instead of a numeric matrix. This is because PCG, like many of the other iterative methods, uses the matrix-vector product A*x in its calculation, so it doesn't necessarily require A to perform its duties, just the result of that multiplication.
To do this you need to write a function with the form:
function y = afun(x)
%put commands here
end
This function is called by PCG to evaluate A*x, so PCG provides the input vector x and the value of y returned by the function needs to be equal to A*x.
After you write the function you just need to specify it as the first input to PCG rather than providing a numeric matrix:
x = pcg(@afun,b)
Adding Parameters
PCG expects the function handle for A to have a single input for x, so if you need to use more than one input to that function to use variables in the workspace then it requires that you pass the function handle to PCG differently.
In this case you would write the function with however many inputs you need:
function y = afun(x,p1,p2,p3)
%put commands here
end
Then, the call to the solver becomes:
p1 = 1;
p2 = 2;
p3 = 3;
myA = @(x) afun(x,p1,p2,p3);
x = pcg(myA,b)
Notice that myA is an anonymous function that calls afun with 1 input, x. The values of p1, p2, and p3 are taken from the workspace when myA is called.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!