필터 지우기
필터 지우기

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 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