Hello. Is it possible to have an anonymous function combined with an If statement in a non-regression function? something like this --->
tbl = table(x1, x2, x3, y);
if table.x1 < 30
modelfun1 = @(b,x)(...Equation (1)...);
b0 = [1 1 1 ...];
else % table.x1 > 30
modelfun2 = @(b,x)(...Equation (2)...);
b0 = [1 1 1...];
mdl1 = fitnlm(tbl, modelfun1, b0)
mdl2 = fitnlm(tbl, modelfun2, b0)
end

 채택된 답변

Star Strider
Star Strider 2017년 6월 5일

1 개 추천

Not an if statement. However you can use a form of ‘logical indexing’ to do essentially the same thing.
Example
x = linspace(0, 60);
b = [3 11];
modelfun = @(b,x) (x<=30).*(b(1).*x/10 - b(2)) + (x>30).*(b(1).*sin(x.*b(2)));
figure(1)
plot(x, modelfun(b,x))
grid
Logical vectors evaluate as (0,1) numeric values in calculations.

댓글 수: 4

wesleynotwise
wesleynotwise 2017년 6월 5일
IT WORKS LIKE MAGIC in the fitnlm function too. Thanks once again.
Sidetrack 1: I assume this also applies to categorical variable? eg: (x =='apple').*(b(1)...)
Sidetrack 2: why IF statement can't be used in this case?
Star Strider
Star Strider 2017년 6월 5일
As always, my pleasure.
  1. I never tried it with categorical variables. In any event, you will need to use the strcmp (link) or strcmpi (link) functions to do string comparisons.
  2. The if block is not an option for anonymous functions due to the restrictions on anonymous function syntax. You could use if blocks in function files, however, since they use the syntax rules for scripts. The documentation on Anonymous Functions (link) offers further clarification.
wesleynotwise
wesleynotwise 2017년 6월 5일
Noted. Cheers.
Star Strider
Star Strider 2017년 6월 5일
Cheers.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Live Scripts and Functions에 대해 자세히 알아보기

질문:

2017년 6월 5일

댓글:

2017년 6월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by