Sum up function handle
20 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
D Frey
el 16 de Dic. de 2017
Respondida: Daniel Huang
el 3 de Jun. de 2020
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 comentarios
Respuesta aceptada
YT
el 16 de Dic. de 2017
Editada: YT
el 16 de Dic. de 2017
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 comentarios
Más respuestas (1)
Daniel Huang
el 3 de Jun. de 2020
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 comentarios
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!