Anonymous function from for loop

조회 수: 10 (최근 30일)
Gethal
Gethal 2014년 10월 28일
댓글: Gethal 2014년 10월 28일
Hello, I am having trouble creating an anonymous function matrix using a for loop. My code looks like this:
n=4; %Or w/e number. Could be 100.
for i = 1:n
f{i,1} = @(x) (x.^i).*(1-x)
end
The output is this:
f =
@(x)(x.^i).*(1-x)
@(x)(x.^i).*(1-x)
@(x)(x.^i).*(1-x)
@(x)(x.^i).*(1-x)
The problem is that the "i" is not changing. It should look like this:
f =
@(x)(x.^1).*(1-x)
@(x)(x.^2).*(1-x)
@(x)(x.^3).*(1-x)
@(x)(x.^4).*(1-x)
Any ideas? Also, I will later have to take the derivative of each row. Is there a simple way to do it? Like this maybe:
derivative(1) = der(f{1})
derivative(2) = der(f{2})
Thanks in advance!

채택된 답변

Sean de Wolski
Sean de Wolski 2014년 10월 28일
편집: Sean de Wolski 2014년 10월 28일
Although it is showing i, as the variable, this is actually hardwired to the numeric value.
for ii = 1:n
feval(f{ii},pi)
end
Yields:
ans =
-6.7280
ans =
-21.1367
ans =
-66.4028
ans =
-208.6106
In order to see the value for the captured variables in the anonymous function, you can use functions
fns = functions(f{1})
fns.workspace{1}
In order to take the derivative analytically, I would use Symbolic Math and syms
syms x ix
f = (x.^i).*(1-x)
f =
-x^4*(x - 1)
diff(f,x)
ans =
- 4*x^3*(x - 1) - x^4

추가 답변 (1개)

Gethal
Gethal 2014년 10월 28일
Thanks. After doing a lot of research and also reading your answer I have come to a conclusion. I will not use anonymous functions because they don't work well with other MATLAB functions. For example, I cant just multiply an anonymous function by a constant because it says:
Undefined function 'times' for input arguments of type 'function_handle'.
Anonymous functions become too complicated to handle (pun intended). I rather work with other simpler methods. Thanks though. I will look into using symbolic commands. Also thanks for the quick answer.
  댓글 수: 2
Sean de Wolski
Sean de Wolski 2014년 10월 28일
You can multiply the output of anonymous functions
f(1)*f(2)
But since the function requires an input, multiplying it directly doesn't work. It sounds to me like the symbolic approach is the best for your overall use case. Solve everything symbolically and then subs in the values when you need them.
Gethal
Gethal 2014년 10월 28일
Will try. Thanks

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by