Using the clear command in functions?

조회 수: 177 (최근 30일)
Spaceman
Spaceman 2024년 3월 14일
댓글: Spaceman 2024년 4월 8일
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
Stephen23
Stephen23 2024년 3월 14일
편집: Stephen23 2024년 3월 14일
"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.
Spaceman
Spaceman 2024년 3월 14일
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
Rik
Rik 2024년 3월 19일
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).
Spaceman
Spaceman 2024년 4월 8일
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개)

KSSV
KSSV 2024년 3월 14일
Becuase
clc, clear
clears your input variables which are saved in the workspace. You need not to use it inside the function.
  댓글 수: 6
Steven Lord
Steven Lord 2024년 3월 21일
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.
Spaceman
Spaceman 2024년 4월 8일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by