In this article, we are going to discuss “Clearing items from Memory”, in MATLAB which can be done using clear operation.
The clear operation is used to clear the specified items from memory or from the currently active workspace. It is used to free up the system memory.
Syntax:
clear
clear name1 … nameN
clear -regexp expr1 … exprN
clear(‘a’, ‘b’, ‘c’)
clear([‘a’ ‘b’ ‘c’])
clear functions
clear mex
clear global
clear all
clear keyword
Here,
- clear: This is used to remove all items from the current workspace.
- clear name1, … nameN: This is used to remove the variables such as name1 … nameN from memory.
- clear -regexp expr1 … exprN: This is used to remove all variables matching any of the regular expressions listed. This is used to remove variables only.
- clear(‘a’, ‘b’, ‘c’) and clear([‘a’ ‘b’ ‘c’]): This is used to remove its variables if the specified variables exist in the local environment of the current function.
- clear functions: This is used to remove unlocked functions only. If a function is locked or currently running, it is not cleared from memory.
- clear mex: This is used to clear all MEX files from memory.
- clear global: This is used to clear all global variables.
- clear all: This is used to remove all variables, functions, and MEX files from memory.
- clear keyword: This is used to clear the items indicated by the keyword.
Example 1:
Matlab
A = 2;
B = 4;
C = 6;
D = 8;
clear
whos
|
This example will clear all the values.
Example 2:
Matlab
A = 2;
B = 4;
C = 6;
D = 8;
clear B D;
whos
|
Output:
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
A 1x1 8 double
C 1x1 8 double
Total is 2 elements using 16 bytes
Example 3:
Matlab
exp1 = 'ab+c' ;
exp2 = 'a-c' ;
exp3 = '+/gfg' ;
clear -regexp ^exp2;
whos
|
Output:
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
exp1 1x4 4 char
exp3 1x5 5 char
Total is 9 elements using 9 bytes
Example 4:
Matlab
A = 2;
B = 4;
C = 6;
D = 8;
clear ( 'A' , 'C' );
clear ([ 'D' ]);
whos
|
Output:
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
B 1x1 8 double
Total is 1 element using 8 bytes
Example 5:
Matlab
global A;
A = 2;
B = 4;
C = 6;
D = 8;
clear global
whos
|
Output:
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
B 1x1 8 double
C 1x1 8 double
D 1x1 8 double
Total is 3 elements using 24 bytes
Example 6:
Matlab
global A;
A = 2;
B = 4;
keyword = 6;
D = 8;
clear keyword
whos
|
Output:
Variables in the current scope:
Attr Name Size Bytes Class
==== ==== ==== ===== =====
g A 1x1 8 double
B 1x1 8 double
D 1x1 8 double
Total is 3 elements using 24 bytes
Example 7:
Matlab
global A;
A = 2;
B = 4;
keyword = 6;
D = 8;
clear all
whos
|
This example will clear all the values.