Borrar filtros
Borrar filtros

How can I delete variables in my MAT-file without loading them into MATLAB 7.2 (R2006a)?

71 visualizaciones (últimos 30 días)
I would like to delete variables in a MAT-file without loading them into MATLAB first.
For example, I have a file called myFile.mat which contains many variables resulting in a large MAT-file which is slow to load. I don't need all of the variables in the file.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 10 de Nov. de 2015
MATLAB itself does not offer any functionality for deleting a particular variable from a MAT file.
 
However the MAT FILE API provides the matDeleteVariable function which allows you to delete a variable from a MAT file by its name. You can create a small MEX function in order to call matDeleteVariable. An example is attached.
 
  2 comentarios
Matt J
Matt J el 28 de Jul. de 2017
Editada: Matt J el 28 de Jul. de 2017
It would also be nice to have a way of renaming variables in MAT files. Is there any API function to allow that?
Matt J
Matt J el 28 de Jul. de 2017
I tweaked the code to allow multiple variables to be deleted in a single call, in case anyone finds it useful.
#include "mex.h"
#include "mat.h"
/* This function removes one or more variables from a MAT file
* Compile it with
* >>mex rmvarMatfileMEX.c
* Afterwards call it with
* >> rmvarMatfileMEX(FILENAME_WITH_EXTENSION,...variables....)
* e.g.
* >> rmvarMatfileMEX('MyFile.mat','var1','var2',...)
*/
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
MATFile *f;
char *filename;
char *vname;
int tmp;
if (nrhs >= 2 )
{
if (!mxIsChar(prhs[0]) || !mxIsChar(prhs[0]))
{
mexErrMsgIdAndTxt("RemoveVariableFromMatFile:ClassInputArguments","This function expects the inputs to be char.");
}
filename = mxArrayToString(prhs[0]);
f = matOpen(filename,"u");
if (f == NULL)
{
mxFree(filename);
mexErrMsgIdAndTxt("RemoveVariableFromMatFile:UnableToOpenFile","Could not open file. Make sure the file exists and is accessible.");
}
for (int i=1;i<nrhs;i++)
{
vname = mxArrayToString(prhs[i]);
tmp = matDeleteVariable(f,vname);
if ( tmp != 0)
{
mexWarnMsgIdAndTxt("RemoveVariableFromMatFile:UnableToDeleteVariable","Could not delete variable. Make sure that the variable exists.");
}
mxFree(vname);
vname=NULL;
}
matClose(f);
mxFree(filename);
}
}

Iniciar sesión para comentar.

Más respuestas (1)

David szpliman
David szpliman el 19 de Sept. de 2018

Great Genius! Problem solved!

Categorías

Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.

Productos


Versión

R2006a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by