anonymous function does not calculate a numbers

1 view (last 30 days)
% 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.

Accepted Answer

Walter Roberson
Walter Roberson on 27 Nov 2012
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.

More Answers (1)

Abdulaziz
Abdulaziz on 27 Nov 2012
Thank you Walter as usually you always give the best easy to understand answers.

Community Treasure Hunt

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

Start Hunting!