I have in my file .mat three matrices, I need to delete one of them.
I try clear ('Matrice1')
, but it doesn't work.
I have in my file .mat three matrices, I need to delete one of them.
I try clear ('Matrice1')
, but it doesn't work.
The closest thing to deleting a variable I can think of is replacing it with an empty array. If this is acceptable, you can either do it with the methods in the question Sardar_Usama mentioned, or using matfile
like so:
% Let's say the mat-file is called "matlab.mat"
a = matfile('H:\PathToFile\matlab.mat','Writable',true)
Output:
a =
matlab.io.MatFile
Properties:
Properties.Source: 'H:\PathToFile\matlab.mat'
Properties.Writable: true
SIZE_X: [1x1 double]
SIZE_Y: [1x1 double]
Then you can do:
a.SIZE_X = []
And get:
a =
matlab.io.MatFile
Properties:
Properties.Source: 'H:\PathToFile\matlab.mat'
Properties.Writable: true
SIZE_X: [0x0 double]
SIZE_Y: [1x1 double]
After doing this, no further actions are required. The variable inside the file will have the new value ([]
in this case).
I'm providing this answer because the linked question is from ~6 years ago, when the matfile
option didn't exist yet (added in R2011b).
If you absolutely must completely delete the entire variable the most straightforward option is to load the data, remove the variable, and then resave it. Because we have to load and save again, this method is very likely far less efficient than using memmapfile
or using save
to change the stored variable to an empty array.
For example:
function testcode
% Generate sample data
a = rand(12);
b = rand(12);
c = rand(12);
save('test.mat');
% Remove and test
rmmatvar('test.mat', 'c');
whos('-file', 'test.mat');
end
function rmmatvar(matfile, varname)
% Load in data as a structure, where every field corresponds to a variable
% Then remove the field corresponding to the variable
tmp = rmfield(load(matfile), varname);
% Resave, '-struct' flag tells MATLAB to store the fields as distinct variables
save(matfile, '-struct', 'tmp');
end
Which gives the following output:
Name Size Bytes Class Attributes
a 12x12 1152 double
b 12x12 1152 double