How to replace variable names in a mat file

152 views (last 30 days)
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

Accepted Answer

Adam
Adam on 8 May 2015
Edited: Adam on 8 May 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.

More Answers (2)

CAM
CAM on 8 May 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

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

Tags

Community Treasure Hunt

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

Start Hunting!