Cell array of anonymous functions to vector anonymous function

4 visualizaciones (últimos 30 días)
P.C.
P.C. el 3 de Sept. de 2020
Editada: Bruno Luong el 3 de Sept. de 2020
I have the following problem: Let's say I have a 1xn cell array called f, that means f{i}(x)=fi(x) gives a function of x for each index i. Is there a way other than using arrayfun to make a vector function out of this, that means to get an anonymous function like f2=@(x) [f{1}(x) f{2}(x) ... f{n}(x)] without having to type it manually? I managed that with arrayfun, but as I use this function a lot, arrayfun takes way too long compared to typing it out manually as I did for f2.
  7 comentarios
P.C.
P.C. el 3 de Sept. de 2020
Editada: P.C. el 3 de Sept. de 2020
The functions I had above were just for demonstration and for n=3, so this does not really work for say n=100. The functions I have are also not analytical, but obtained from an interpolation.
Dana
Dana el 3 de Sept. de 2020
Can you post code doing this with arrayfun? I'm not entirely clear on what the inptus/output here all are.

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 3 de Sept. de 2020
The functions I had above were just for demonstration and for n=3, so this does not really work for say n=100.
In situations where you have hundereds of functions, it is normally because you have overlooked vector-valued, vectorized alternatives. For example, instead of
f{1}=@(x) x^1
f{2}=@(x) x^2
f{3}=@(x) x^3
...
f{100}=@(x) x^100
you should really have a single vectorized function,
f=@(x) x.^(1:100)
  23 comentarios
P.C.
P.C. el 3 de Sept. de 2020
I did use it as an anonymous function though like in Matt's code. Does it make a difference if you call the tq separately one by one instead of all in one call? Maybe I did something wrong, but I pretty much just replaced my loop with the one line.
Bruno Luong
Bruno Luong el 3 de Sept. de 2020
Editada: Bruno Luong el 3 de Sept. de 2020
The difference is noise
tic
interfun = @(tq) interp1(t,c,tq);
ci2 = interfun(tq);
toc % Elapsed time is 0.063195 seconds.
Why you want to call one by one? Do you prefer to get your result in 70 ms or 15 minutes?

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Performance and Memory en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by