【发布时间】:2018-10-09 14:34:54
【问题描述】:
我正在尝试将函数句柄输入到我在下面创建的函数中。我不完全确定如何做到这一点。 例如,我如何获得:
conjugate_gradient(@(y) ABC(y), column_vector, initial_guess)
不会出错? 如果我以同样的方式使用 matlab 的 pcg 函数,它将起作用:
pcg(@(y) ABC(y),b,tol).
我尝试阅读 pcg 函数,他们确实在函数描述中考虑了这一点,但是我对 MATLAB 仍然非常缺乏经验,我们应该说难以理解他们所做的事情。谢谢!
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
【问题讨论】:
-
你得到的错误是什么?我怀疑这是因为您的
matrix参数不是矩阵。您可能需要从函数中获取 返回值 以获得某些输入值y并使用它。 -
如果你的函数
ABC(y)返回一个矩阵,而矩阵是conjugate_gradient所期望的,那么你应该这样称呼它:conjugate_gradient(ABC(y), column_vector, initial_guess)。这样,您将矩阵发送到您的函数,而不是函数句柄。