- Use functions for any code that is used for more than one day.
- Avoid CLEAR & CLOSE & CLC in code.
Using the clear command in functions?
177 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
So I was practicing functions. . . My habit for writing scripts is to put clear, clc, close all before every section, unless variables are carrying over, to keep everything "cleaned up".
My question is, when I put clear in a function it gives me a statement saying it reduces code performance and is often not needed.
Why is this the case for functions but not scripts?
Also in my example function below, any reason why I am getting an error when calling it? (I used clear here to show what I mean)
function m_kg=lb2kg_ZLKW(w_lb)
% converts weight in lbs to mass in kg
clc, clear
m_kg=1/2.2.*w_lb;
end
% code to call function: w_lb=0:1:100; m_kg=lb2kg_ZLKW(w_lb);
2 commentaires
Stephen23
le 14 Mar 2024
Modifié(e) : Stephen23
le 14 Mar 2024
"My habit for writing scripts is to put clear, clc, close all before every section, unless variables are carrying over, to keep everything "cleaned up"."
Habits like this just need to be unlearned later. This is what you are finding out now.
Much better habits:
"My question is, when I put clear in a function it gives me a statement saying it reduces code performance and is often not needed."
Because it reduces code performance and is often not needed.
"Why is this the case for functions but not scripts?"
Many experienced users would argue that this is always the case.
"Also in my example function below, any reason why I am getting an error when calling it?"
Because you have learned some bad habits (e.g. automatically writing CLEAR & CLOSE & CLC at the start of everything that you write):
Why are you going to CLEAR the workspace of a function? At best it does absolutely nothing (because the workspace is fresh and new anyway) and at worst it will cause pointless bugs (like your example here, where you clear the input arguments and thus make the function completely uncallable).
CLEAR should be called sparingly, most often only from the command line when trying things out. Only rarely does CLEAR need to be called in code... and even then, you are probably really wanting to call CLEARVARS and not CLEAR.
CLC should also be avoided: when you call SIN(PI) does it clear the command window? (hint: no) Then why does your function need to? Ditto for CLOSE. Do not mix up different functionalities in one function.
Réponse acceptée
Shubham
le 14 Mar 2024
Hi Kyle,
The warning about using clear inside functions and the reason it's discouraged compared to its use in scripts boil down to how MATLAB manages memory and workspace environments between scripts and functions.
Scripts vs. Functions
- Scripts operate in the base workspace. This means they can access and modify any variable in the base workspace. Using clear in scripts can be a way to manage the workspace by removing unnecessary variables, thus potentially freeing up memory and avoiding conflicts or unintended use of variables.
- Functions, on the other hand, operate in their own isolated workspace. When a function is called, MATLAB creates a new workspace for that function. Variables created within a function are local to that function and do not persist after the function has finished executing, unless they are returned as output. This isolation inherently "cleans up" after the function without needing to use clear. The moment the function execution is completed, all local variables are cleared automatically.
Performance Concerns
- When you use clear within a function, you are forcing MATLAB to perform an additional operation that is, in most cases, unnecessary due to the natural behavior of function workspaces. This can slightly degrade performance, especially if the function is called repeatedly in a loop or a large dataset is being processed. MATLAB's warning about clear reducing code performance is highlighting this inefficiency.
Error in Your Function
Regarding the error you're encountering when calling your function, the function definition itself looks syntactically correct. However, using clc and clear inside the function is not advisable for the reasons mentioned above. The clc command clears the Command Window's content, which is generally harmless but unnecessary for the function's operation. The clear command is likely what's triggering the warning about reduced code performance.
If you're encountering a specific runtime error (not just the warning about clear), it could be due to how you're calling the function or an environment-specific issue. The code snippet you provided for calling the function looks correct and should work as intended for converting weights from pounds to kilograms.
To avoid the warning and ensure optimal performance, you can simply remove clc, clear from your function.
3 commentaires
Rik
le 19 Mar 2024
Just a note: scripts don't work in the base workspace, they work in the calling workspace. You can call a script from a function as well (although you shouldn't, because you shouldn't use scripts for work).
Plus de réponses (1)
KSSV
le 14 Mar 2024
Becuase
clc, clear
clears your input variables which are saved in the workspace. You need not to use it inside the function.
6 commentaires
Steven Lord
le 21 Mar 2024
Well, clc clears the command window, which I like when starting a script in case I was working beforehand just to clean things up.
IMO choosing to run clc yourself before running a script is fine.
But putting it inside a script so it runs automatically will prevent you from running a script twice to compare the results visually. "Okay, that almost did what I wanted. Let me change one line and rerun the code to see which set of results is better." If the display has been automatically cleared by the script, the previous results may have been lost.
Voir également
Catégories
En savoir plus sur Logical 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!