【问题标题】:How to delete a variable from .mat file in matlab?如何从matlab中的.mat文件中删除一个变量?
【发布时间】:2017-01-02 03:29:21
【问题描述】:

我的文件 .mat 中有三个矩阵,我需要删除其中一个。

我尝试clear ('Matrice1'),但它不起作用。

【问题讨论】:

  • 这不是一个重复的问题,在那个链接之前的问题是程序员在新执行后无法保存所有结果,所以解决方案是添加'-append'但是在我的情况下,我只需要从已经存在的 .mat 文件中删除一个变量。
  • [] 重写变量会删除该变量。他们使用 append 用[] 重写变量。
  • @NKN 不完全是。该变量仍然存在于文件中,但它的 contents 现在是一个空数组。
  • @NKN 不。这就是为什么我说“如果可以接受”。顺便说一句,另一个相关问题:stackoverflow.com/q/35323694/3372061。还有this FEX submission

标签: matlab file-io data-storage file-access mat-file


【解决方案1】:

如果您绝对必须完全删除整个变量,最直接的选择是加载数据,删除变量,然后重新保存。因为我们必须再次加载和保存,所以这种方法很可能远不如使用memmapfile 或使用save 将存储的变量更改为空数组。

例如:

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

它给出以下输出:

  Name       Size            Bytes  Class     Attributes

  a         12x12             1152  double              
  b         12x12             1152  double      

【讨论】:

  • 不是模糊工具箱中的rmvar 和映射工具箱中的rmfield 的函数吗? (+1)
【解决方案2】:

我能想到的最接近删除变量的方法是将其替换为空数组。如果这是可以接受的,您可以使用 question Sardar_Usama 中提到的方法,或者像这样使用 matfile

% Let's say the mat-file is called "matlab.mat"
a = matfile('H:\PathToFile\matlab.mat','Writable',true)

输出:

a = 

  matlab.io.MatFile

  Properties:
      Properties.Source: 'H:\PathToFile\matlab.mat'
    Properties.Writable: true                                          
                 SIZE_X: [1x1 double]                                  
                 SIZE_Y: [1x1 double]  

那么你可以这样做:

a.SIZE_X = []

得到:

a = 

  matlab.io.MatFile

  Properties:
      Properties.Source: 'H:\PathToFile\matlab.mat'
    Properties.Writable: true                                          
                 SIZE_X: [0x0 double]                                  
                 SIZE_Y: [1x1 double] 

执行此操作后,无需进一步操作。文件中的变量将具有新值(在本例中为[])。


附言

我提供这个答案是因为链接的问题来自大约 6 年前,当时matfile 选项还不存在(在 R2011b 中添加)。

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多