1

I am using a toolbox in MATLAB and I'm not ready to make any change to the functions within it.

Let's say that it has a function f = @(x,l) g(x)*h(l)

I want to call f at different x but always the same l:

l = 3;
f2(x) = @(x) f(x,l);
for i=1:length(x)
   f2(x(i));
end

However, if I do this, the function h will be called at l=3 for each i. I would like MATLAB to know when I defined f2 that h(l) can be stored and that actually f2(x) = 3*g(x)
Is there a way around this problem ? or do I need to go into the code of f2 and write somewhere:

A = h(l);
f2 = @(x) A*g(x)
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Ludo M
  • 15
  • 4
  • Your last sentence is the answer to your question. The value of `A` will be statically stored in the workspace of `f2()` at the time you define your function `f2 = @(x) A*g(x)`. – Hoki Feb 28 '19 at 15:44
  • Yes but i would need to look where in the toolbox there is `f(x,l) = g(x)*h(l)` and as i said, I'm not willing to change anything in the toolbox as there might be multiple times where it is more suitable to store the function output than calling it everytime. – Ludo M Feb 28 '19 at 15:55
  • you don't need to change anything in the toolbox itself. You just need to look at it to identify `g(x)` and `h(l)`. Once it is done, calculate `A=h(3);`, then overload the toolbox function `f()` with your own new definition of `f = @(x) A*g(x)` – Hoki Feb 28 '19 at 16:04
  • Yes, it would work, the thing is that i don't want to look for the exact line where `f` is defined. Instead, i am looking for a generic way to make sure when i am calling a function `f2 = @(x)f(x,l)` , that sub-functions within `f` that depend only on `l` are stored to optimize CPU time. – Ludo M Feb 28 '19 at 16:25

1 Answers1

0

why not define your function as?

f2 = @(x) f(x,3)
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • If it do it this way, MATLAB won't store `h(3)` but will call `h` everytime i call `f2` at a new `x`. – Ludo M Feb 28 '19 at 16:09
  • Yes, if that's what you want to prevent I don't see any workaround other than redefining the referred function. What you want is *memoization* on the second argument. – karakfa Feb 28 '19 at 16:32
  • @LudoM Related to karakfa comment above, see https://www.mathworks.com/help/matlab/ref/memoize.html – Luis Mendo Feb 28 '19 at 17:32