1

I am trying to feed a function handle into the function I created below. I'm not exactly sure how to do this. For example, how do I get:

conjugate_gradient(@(y) ABC(y), column_vector, initial_guess)

to not error? If I use matlab's pcg function in the same way it will work:

pcg(@(y) ABC(y),b,tol).

I tried reading the pcg function, and they do take about this in the function description, however I'm still super inexperienced with MATLAB and had shall we say some difficulty understanding what they did.Thank You!

function [x] = conjugate_gradient(matrix, column_vector, initial_guess)

    y = [];
    col_size = length(column_vector);
    temp = size(matrix);
    mat_row_len = temp(2);
%         algorithm:

    r_cur = column_vector - matrix * initial_guess;
    p = r_cur;
    k = 0;
    x_approx = initial_guess;

    for i=1:mat_row_len        
        alpha = ( r_cur.' * r_cur ) / (p.' *(matrix* p));
        x_approx = x_approx + alpha * p;
        r_next = r_cur - alpha*(matrix * p);
        fprintf(num2str(r_next'*r_next), num2str(i))
        y = [y; i, r_next'*r_next];
        %exit condition
        if sqrt(r_next'*r_next) < 1e-2
            y
              break;
        end
        beta = (r_next.'* r_next )/(r_cur.' * (r_cur) );
        p = r_next + beta * p;
        k = k+1;

        r_cur = r_next;
    end
    y
    [x] = x_approx;
end
SomeDude
  • 17
  • 1
  • What is the error you get? I suspect it's because your `matrix` argument is not a matrix. You probably need to get the *return value* from the function for some input value `y` and work with that. – beaker Apr 29 '18 at 15:03
  • if your function `ABC(y)` returns a matrix, and a matrix is what is expected in `conjugate_gradient`, then you should call it that way: `conjugate_gradient(ABC(y), column_vector, initial_guess)`. This way you send a matrix to your function, not a function handle. – Hoki May 01 '18 at 09:03

1 Answers1

0

When you do

f = @(y) ABC(y)

You create a function handle. (Note that in this case it's the same as f=@ABC). This handle is a variable, and this can be passed to a function, but is otherwise the same as the function. Thus:

f(1)

is the same as calling

ABC(1)

You pass this handle to a function as the first argument, which you have called matrix. This seems misleading, as the variable matrix will now be a function handle, not a matrix. Inside your function you can do matrix(y) and evaluate the function for y.

However, reading your function, it seems that you treat the matrix input as an actual matrix. This is why you get errors. You cannot multiply it by a vector and expect a result!

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120