How to replace variable names in a mat file

113 次查看(过去 30 天)
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

采纳的回答

Adam
Adam 2015-5-8
编辑:Adam 2015-5-8
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.

更多回答(2 个)

CAM
CAM 2015-5-8
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 2022-6-23
Thank you so much @Adam & @CAM for your answers !

类别

Help CenterFile Exchange 中查找有关 Workspace Variables and MAT-Files 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by