Differentiating a symbolic function by a lot of variables without loop.
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Samyon Shahnovitch
le 23 Fév 2017
Commenté : Samyon Shahnovitch
le 24 Fév 2017
Hello. I am trying to create a script to calculate a function error (sqrt(sum(df/dvar * delta var)^2)) [Physics lab course] so I need to differentiate by a different variable each time. If I do this with a for loop, it works. If i try to do this:
exp = sum((diff(f, mat(:, 1))*mat(:, 2)).^2) % Symbolic Expression
it gives this error:
The second argument must be a variable or a nonnegative integer specifying the number of differentiations.
If fore example I change it for diff(f, mat(1, 1)) it gives no error (but differentiates by the same variable of course..)
So, any Ideas how could I do this w/o a loop? thank you! (The loop is:)
for k=1:size(mat, 1);
exp = exp+(diff(f, mat(k, 1))*mat(k, 2))^2;
end
0 commentaires
Réponse acceptée
John D'Errico
le 23 Fév 2017
Modifié(e) : John D'Errico
le 23 Fév 2017
Often people do things in MATLAB where they use loops excessively. So we seee code with heavily nested loops, when a simple matrix multiply would suffice.
Other times, I see people who seem terrified of loops, as if a simple loop is a bad thing. You are doing the same operations in any case, so a loop or not will not be more efficient here. And very often code that is written to avoid a loop at all costs is terribly difficult to read, difficult to debug.
In this case, the loop is simple. Easy to read and write. So why is there a need to avoid this loop? Just use the loop, and go on to the next part of your code.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!