anonymous function does not calculate a numbers
1 次查看(过去 30 天)
显示 更早的评论
% Hi guys please I need help with an issue I could not figure.
>> % This is simplified example of my issue
>> for i=1:5
y=i*x^2;
dy=diff(y,x);
g=@(x)dy;% this equation is changing in each iteration due to 'i'.
m=g(i)
end
m =2*x
the anonymous function does not account for the i, it always gives the variable x in the m equation.
0 个评论
采纳的回答
Walter Roberson
2012-11-27
You are overwriting "m" on each iteration of the "for i" loop.
Should we assume that "x" is defined as a symbol?
Please check that "i" is the variable name being used in your loop. Using "i" as a variable name is not a good idea as it clashes with the use of "i" meaning the square root of negative 1.
Note that the "x" of @(x) will not be the same "x" as in "dy". When a dummy argument name is used in an anonymous function, the dummy argument value will only be substituted for variables with that name that occur literally in the anonymous function body. You could, for example, use
g = @(x) subs(dy, 'x', x)
provided that dy is symbolic.
0 个评论
更多回答(1 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!