Sum up function handle
20 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!