Evaluate a changing expression in loop
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Kristoffer Lindvall
il 11 Gen 2016
Commentato: Kristoffer Lindvall
il 12 Gen 2016
Hi! I am writing a code that generates a function f in a loop. This function f changes in every loop, for example from f = x + 2*x to f = 3*x^2 + 1 (randomly), and I want to evaluate f at different points in every loop. I have tried using subs, eval/feval, matlabFunction etc but it is still running slowly. How would you tackle a problem like this in the most efficient way?
0 Commenti
Risposta accettata
Stephen23
il 11 Gen 2016
Modificato: Stephen23
il 11 Gen 2016
It all depends on what you mean by "random": surely there must be some limit to the power or coefficient, and a limit to the number of addends? What distribution do these values have?
The two examples that you show both have two addends, and each addend is a low order power of x with a coefficient. If these are indicative of all of your functions, then why not use MATLAB effectively, instead of trying to fight it with evil eval? MATLAB works best with matrices, so lets try using them! Simply generate all of the coefficients, powers, etc into matrices, and calculate the function once, when required. This will be much faster and more efficient than generating "random" functions in a loop and evaluating them.
Here is an example showing twenty (5x4) independent, random functions, all calculated simultaneously by using 5x4 arrays for the function coefficients and powers.
>> cof = randi(4,5,4,2)-1; % all 20+20 coefficients
>> pwr = randi(4,5,4,2)-1; % all 20+20 powers
>> F = @(x)cof(:,:,1).*x.^pwr(:,:,1) + cof(:,:,2).*x.^pwr(:,:,2);
>> F(1) % all 20 functions at x=1
ans =
2 1 6 0
3 4 3 3
3 5 1 3
4 3 3 2
1 0 1 0
>> F(2) % all 20 functions at x=2
ans =
9 2 24 0
6 16 6 24
6 20 4 12
7 16 6 8
2 0 4 0
Lets have a look in more detail at the first element of the output. The coefficients and powers of its two addends are:
>> cof(1,1,:)
ans(:,:,1) =
1
ans(:,:,2) =
1
>> pwr(1,1,:)
ans(:,:,1) =
0
ans(:,:,2) =
3
Note that the pwr of zero makes this addend a constant, equal to cof(1,1,1), because x^0 is one. So for x==2, the first element is thus:
cof(1,1,1)*2^pwr(1,1,1) + cof(1,1,2)*2^pwr(1,1,2)
which is:
1*2^0 + 1*2^3
which is:
1*1 + 1*8
which is equal to
9
the same as the matrix shows for the first element (at x==2).
9 Commenti
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!