Using the clear command in functions?

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 个评论

"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:
  • Use functions for any code that is used for more than one day.
  • Avoid CLEAR & CLOSE & CLC in code.
"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.
I am unfortunately part of the Cargo cult programming style. I am certainly an abuser of comments.

请先登录,再进行评论。

 采纳的回答

Shubham
Shubham 2024-3-14
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 个评论

Thank you for your explanation. This all makes very much more sense to me now.
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).
I am learning the nuances more and more each day, and there are many. It's interesting how there is not one universal coding language, just like there is not one universal language of the human race.

请先登录,再进行评论。

更多回答(1 个)

Becuase
clc, clear
clears your input variables which are saved in the workspace. You need not to use it inside the function.

6 个评论

Need it be used ever in script writing? Do I need a comma, or semicolon; or can I just put a space between clc clear?
You should question why you are using these. What do you want to achieve? They do something specific. Did you read the documentation to figure out if you actually want that to happen?
And what is the difference between a comma and a semicolon in Matlab?
Can you now answer your own questions? Feel free to post a comment if not.
Well, clc clears the command window, which I like when starting a script in case I was working beforehand just to clean things up. Clear clears the entire workspace, which is apparently the 'calling workspace' which I normally want when starting to write a new script so there aren't any confusions with variables. A semicolon terminates a statement thereby surpressing it, and a coma will allow the statement to be shown or to seperate data points, etc.. But spaces can also do that. A=[2 3] or A=[2, 3]
Close, but some details (which can sometimes be relevant) are not quite correct.
A statement can be terminated by a newline, a comma, or a semicolon. if a variable is assigned, the results are printed to the command window for newline and comma, but not semicolon.
Creating arrays is a different context, where newline and semicolon denote a new row, while comma and space denote a new column.
A space does not separate two commands, but instead enters the command argument mode. This is often used in combination with the cd command to change the active directory (although you should only really need to do so when starting a GUI, and even then only once, and even then it may not be required). That is also why you see the colors change in the editor:
cd,foo
cd bar
As for clear:
If you pause execution in a function (e.g. with a breakpoint) and then use clear, you will clear the variables in that workspace, not the base workspace. That makes clear a powerfull, but dangerous tool. But there is a further nuance: it doesn't just clears variables. If you read the documentation closely, you will notice more categories. Matlab can optimize functions the first time (or first few times) they run. This investment pays out if you run functions many times. clear wipes that cache. If you insist, you can use clearvars to remove previous runs.
My personal opinion is that left-over variables should have no effect. To achieve that, I pre-allocate variables prior to loops, so there is never any confusion (expect when I make a mistake in my code, I'm only human). With good coding practices you should never need clearvars. Obvioulsy this is one of many instances where you need to learn the rules to know when to break them.
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.
Mr. Rik and Mr. Lord, I understand. It's almost a testament to the free will of the code and the person calling the functions or running the scripts. I don't want to automatically do something that might take away that free will due to a bad habit. Thank you for clarifying these modulations.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Function Creation 的更多信息

产品

版本

R2023b

标签

Community Treasure Hunt

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

Start Hunting!

Translated by