Sum up function handle

20 次查看(过去 30 天)
D Frey
D Frey 2017-12-16
Hi,
I got a problem with summing up a function handle in a loop. I want that the fuction handle "error" is summed up for all the different "k" in the loop. In this code the function handle "error" and "sum_error" dont change over the loop iterations. "theta" will be in the end a (6,1) vector.
sum_error = zeros(6,1);
for k = 1:N
error = @(theta)abs(y(k)-phi(k,:)*theta).^2;
sum_error = @(theta)sum_error + error;
end
x0 = zeros(6,1);
[theta_min,~] = fminsearch(sum_error,x0);
The function handle of error shows in every iteration:
@(theta)abs(y(k)-phi(k,:)*theta).^2
I defined y(k) and phi(k,:). Why is it not inserting this values to the function? And why is the summing up not working?
Thanks for your help!
Best

采纳的回答

YT
YT 2017-12-16
编辑:YT 2017-12-16
Although I don't know 'y' and 'phi' (and your 'theta' seems to be constant), I guess it's because you didn't call your 'error' expression with a 'theta' argument
sum_error = sum_error + error(your_theta);
I myself would rewrite it to something like this though (makes it easier I guess)
for k = 1:N
sum_error = sum_error + abs(y(k)-phi(k,:)*theta).^2;
end
  2 个评论
D Frey
D Frey 2017-12-16
Thanks! I didn't take into account that I have to call 'theta' again. I also used your suggested shorter form. There I also needed to call 'theta' in the sum_error:
for k = 1:N
sum_error = sum_error(theta) + abs(y(k)-phi(k,:)*theta).^2;
end
YT
YT 2017-12-16
Glad I could help. Good luck with your project!

请先登录,再进行评论。

更多回答(1 个)

Daniel Huang
Daniel Huang 2020-6-3
From my testing in the current version of Matlab, I think it does plug it in but just doesn't show it in the workspace for some reason. I suspect that it saves a "snapshot" of the value of the variable if not referenced as a variable by the function handle. I don't know exactly what's going on, but my testing code that I used to figure this is:
B = @(x)0;
r = [1 2 3 4 5];
test1 = @(x)x.^2;
for ii = 1:5
B = @(x)test1(x)*r(ii)+B(x);
end
It's weird how the workspace shows the value, but I don't think it's easy to show the actual values for these objects as they are essentially an entire function condensed into one line of code.

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by