Creating an inline-function in dependence of a parameter

조회 수: 3 (최근 30일)
Benjamin
Benjamin 2011년 5월 31일
Hello,
I want to use the newtzero-function which is not able to handle functions with parameters, so I thougth about writing a method which returns an inline function depending on a parameter, for example: fun_gen (5) should return inline('5*x^2').
Any guess?

답변 (3개)

Jonas Reber
Jonas Reber 2011년 5월 31일
maybe str2func is what you are looking for?

Oleg Komarov
Oleg Komarov 2011년 5월 31일
c = 5;
f1 = inline([sprintf('%d',c) '*x^2'])
f2 = str2func(['@(x)' sprintf('%d',c) '*x^2'])
isequal(f1(2),f2(2)) % ok

Walter Roberson
Walter Roberson 2011년 5월 31일
You can do it with anonymous functions instead of inline:
fun_gen = @(c) @(x) c*x^2;
Note that if you do this, then any one generated function will show c when it is displayed instead of the "captured" value of c, but it does work properly.

카테고리

Help CenterFile Exchange에서 Function Handles에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by