Cell array of anonymous functions to vector anonymous function

2 Ansichten (letzte 30 Tage)
P.C.
P.C. am 3 Sep. 2020
Bearbeitet: Bruno Luong am 3 Sep. 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 Kommentare
P.C.
P.C. am 3 Sep. 2020
Bearbeitet: P.C. am 3 Sep. 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 am 3 Sep. 2020
Can you post code doing this with arrayfun? I'm not entirely clear on what the inptus/output here all are.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 3 Sep. 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 Kommentare
P.C.
P.C. am 3 Sep. 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 am 3 Sep. 2020
Bearbeitet: Bruno Luong am 3 Sep. 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?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Performance and Memory finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by