フィルターのクリア

Sum up function handle

20 ビュー (過去 30 日間)
D Frey
D Frey 2017 年 12 月 16 日
回答済み: Daniel Huang 2020 年 6 月 3 日
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 Center および File ExchangeGraphics Object Programming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by