0

In MATLAB: How do I pass a parameter to a function?,

it is said that if i want to pass the parameter u, i need to use anonymous function:

u = 1.2;
[t y] = ode45(@(t, y) ypdiff(t, y, u), [to tf], yo);

Originally, without passing parameter u, the ode line reads:

[t y] = ode45(@ypdiff, [to tf], yo);, where @ypdiff just creates a function handle.

Why if we want to pass u only, we also need to include t and y in the creation of anonymous function @(t, y) ypdiff(t, y, u), but not something like @ypdiff(u)?

Community
  • 1
  • 1
Ka Wa Yip
  • 2,546
  • 3
  • 22
  • 35

1 Answers1

2

Simply appending @ to the front of a function creates a function handle not an anonymous function. This function handle implicitly forwards all input arguments onto the function.

What you need is a function handle to an anonymous function (since it accepts inputs and performs an action or calls another function). In this case, it does not implicitly pass inputs therefore you need to explicitly receive input arguments and then use them (or not) within the anonymous function.

@(t, y)ypdiff(t, y, u)

The only exception to this rule is that some graphics objects will accept a cell array in place of a callback function which accept a function handle as the first element and any additional parameters as the second, but this is not the case for ode45.

{@ypdiff, u}
Suever
  • 64,497
  • 14
  • 82
  • 101
  • but why is t also needed when the derivative does not depend on t? – Ka Wa Yip Oct 07 '16 at 03:13
  • @kww Well you wrote it that way in your initial question. What inputs does `ypdiff` expect? – Suever Oct 07 '16 at 12:10
  • but in case `ypdiff` does not depend on `t`, can `@(t, y)ypdiff(t, y, u)` become `@(y)ypdiff(y, u)`. My objective is to pass `u`. And in MATLAB, it highlights i use `~` to replace `t` in subfunction `ypdiff`. – Ka Wa Yip Oct 07 '16 at 21:09
  • @kww If `ypdiff` only takes two inputs then you can do `@(t,y)ypdiff(y,u)`. You still have to make the anonymous function accept `t`, but you just don't use it when calling `ypdiff` – Suever Oct 07 '16 at 21:12