Input to output variable copies in functions : influence on cpu
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Nicolas Douillet
le 28 Jan 2021
Commenté : Walter Roberson
le 28 Jan 2021
Hi !
One of the advantages of Matlab is its great tolerance on variable names. Meaning you can change the size, the dimension, and even the type of a variable at any time in a script. You can also use the same name for an input and an output variable.
For readability concerns however, when you successively perform a lot of operations on it, it is common (well for me at least) to use for the output variable a different name from the input one. Example :
function var_out = complex_function(var_in)
% Lots of operations on var_in %
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
var_out = var_in;
end
% or
function var_out = complex_function(var_in)
var_out = var_in;
% Lots of operations on var_out
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
end
My question is : is is bad in terms of cpu performances to do such copies ? If yes, what is the best compromise in Matlab between code readability and cpu performance concerning variables use and copies ?
I know it looks very basic a question, but then it is as much important to me to clarify its answer.
Thank you for answer !
Best,
Nicolas
0 commentaires
Réponse acceptée
Walter Roberson
le 28 Jan 2021
It does not matter for cpu purposes whether you copy to a variable first and work on the copy, or if you work on the original and copy at the end.
However, in very restricted contexts, there are some cases where
function var_in = complex_function(var_in)
% Lots of operations on var_in %
% ---------------------------- %
% ---------------------------- %
% ---------------------------- %
end
can be faster. Notice the output variable name is the same as the input variable name. When the moon is in the right phase, and the wind is blowing just right, and you are wearing your lucky 5-leaf clover, then this can save making a deep copy of var_in .
3 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Call Web Services from MATLAB Using HTTP 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!