Does anyone here know how to delete a variable from a matlab file? I know that you can add variables to an existing matlab file using the save -append
method, but there's no documentation on how to delete variables from the file.
Before someone says, "just save it", its because I'm saving intermediate processing steps to disk to alleviate memory problems, and in the end there will be almost 10 GB of intermediate data per analysis routine. Thanks!
To clear one or more specific variables from the current workspace, use clear name1 ... nameN . To clear all variables from the current workspace, use clear or clearvars . To clear all global variables, use clear global or clearvars –global .
To see what variables are stored in a MAT-file before actually loading the file into your workspace, use whos -file filename . This command returns the name, dimensions, size, and data type of all variables in the specified MAT-file. You can use whos -file on binary MAT-files only: whos -file mydata.
Delete variables by variable name. First, specify the unique identifiers in the variable id as observation names. Then, delete the variable id from the dataset array. The dataset array now has six variables.
To store fields of a scalar structure as individual variables, use the save function with the -struct option. This can be useful if you previously loaded variables from a MAT-File into a structure using the syntax S = load( filename ) and want to keep the original variable structure when saving to a new MAT-File.
Interestingly enough, you can use the -append
option with SAVE to effectively erase data from a .mat file. Note this excerpt from the documentation (bold added by me):
For MAT-files,
-append
adds new variables to the file or replaces the saved values of existing variables with values in the workspace.
In other words, if a variable in your .mat file is called A
, you can save over that variable with a new copy of A
(that you've set to []
) using the -append
option. There will still be a variable called A
in the .mat file, but it will be empty and thus reduce the total file size.
Here's an example:
>> A = rand(1000); %# Create a 1000-by-1000 matrix of random values
>> save('savetest.mat','A'); %# Save A to a file
>> whos -file savetest.mat %# Look at the .mat file contents
Name Size Bytes Class Attributes
A 1000x1000 8000000 double
The file size will be about 7.21 MB. Now do this:
>> A = []; %# Set the variable A to empty
>> save('savetest.mat','A','-append'); %# Overwrite A in the file
>> whos -file savetest.mat %# Look at the .mat file contents
Name Size Bytes Class Attributes
A 0x0 0 double
And now the file size will be around 169 bytes. The variable is still in there, but it is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With