How to replace variable names in a mat file

179 visualizaciones (últimos 30 días)
Joseph Stalin
Joseph Stalin el 8 de Mayo de 2015
Respondida: Khalid CHOUA el 23 de Jun. de 2022
Hi, I want to change the naming conventions of a matfile variables. Ex: Original name: CAN_<XXX>_BUS To be changed to: W_YYY_<XXX>_BUS
I am looking for a m script that can read and replace the variables? I prepared a excel sheet with both the namings in a separate column, so that script will search for the existing name and find the name to be replaced. Can anybody help me to do this?
regards, Joseph

Respuesta aceptada

Adam
Adam el 8 de Mayo de 2015
Editada: Adam el 8 de Mayo de 2015
If you load the mat file into a struct (i.e. the load option with output argument), then your variables become fields of that struct which allows you to rename them (renaming variables themselves is not a fun task). You can then save the struct back out to the mat file with the '-struct' flag.
e.g.
varStruct = load( matFile );
...
save( matFile, '-struct', 'varStruct' );
As far as code goes to actually do the structure field renaming though I don't have time personally to do that, but someone else probably will and it should be simple string manipulation with functions such as strrep.
Bear in mind you can access a field name of a struct using a dynamic string as:
myFieldName = getFieldNameStringFromSomewhere();
myStruct.( myFieldName );
rather than having to hard-code the fieldname.

Más respuestas (2)

CAM
CAM el 8 de Mayo de 2015
Adam's answer is the correct algorithm.
Additions:
Use the fieldnames command to get a cell array of field names from the structure. Use strrep to create new field names using the new convention. Finally, create a new structure using the new field names and save it.
% Air code, so please double-check all syntax
fn_old = fieldnames(varStruct);
fn_new = strrep(fn_old, oldStringPart, newStringPart);
for z = 1:length(fn_old)
varStruct_output.(fn_new{z}) = varStruct.(fn_old{z}); % Note the dot-parens notation
end
Hope that helps
  1 comentario
Joseph Stalin
Joseph Stalin el 8 de Mayo de 2015
Thanks for the quick reply. Things start moving from my side.

Iniciar sesión para comentar.


Khalid CHOUA
Khalid CHOUA el 23 de Jun. de 2022
Thank you so much @Adam & @CAM for your answers !

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by