Search code examples
matlabfile-iodata-storagefile-accessmat-file

How to delete a variable from .mat file in matlab?


I have in my file .mat three matrices, I need to delete one of them.

I try clear ('Matrice1'), but it doesn't work.


Solution

  • 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