How to define a variable which won't clear when 'clear' command is used

조회 수: 24 (최근 30일)
Tejas Adsul
Tejas Adsul 2018년 6월 13일
답변: Steven Lord 2018년 6월 13일
I have 5 different scripts, running one after the other, each of which uses some of the variable values from the previous one. To abstain from using a lot of memory, I use clear whenever I can. However, there are some variables which I would like to remain in the workspace all the time. I am using clearvars -except right now, but then I have to write down all those variables which I don't want to clear every time in all the scripts. I would rather like to declare the variable in a way that it cannot be cleared by the general clear command. Is there a way to do so? I haven't tried declaring global variables, since I read too many posts advising against it.
  댓글 수: 2
Rik
Rik 2018년 6월 13일
You should consider making those scripts functions instead. That would automatically clear all variable that are not handed back to the calling function. Using nargin, nargout, varargin, and varargout should help you retain a lot of flexibility.
Tejas Adsul
Tejas Adsul 2018년 6월 13일
Well, I was hesitant to convert them into functions since I would have about 10 input arguments and 5-6 output arguments. But if it takes lesser effort than consistently having to list variables in clearvars, I'll try that.

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

답변 (1개)

Steven Lord
Steven Lord 2018년 6월 13일
With 10 inputs and 5-6 outputs, it's probably going to be pretty easy to accidentally omit one or put one in the wrong order. I would likely turn this script into a function (as others have suggested) and bundle the inputs/outputs into a struct array. That has an additional benefit in that if you decide to enhance your function in such a way that it requires additional information as input or returns additional information as output, you don't need to change the signature of your function. You just need to add a new field to the input struct or access data from the new field of the output struct.

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by