Reputation: 17
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
Upvotes: 1
Views: 58
Reputation: 60761
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!
Upvotes: 0