How to replace variable names in a mat file
106 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joseph Stalin
am 8 Mai 2015
Beantwortet: Khalid CHOUA
am 23 Jun. 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
0 Kommentare
Akzeptierte Antwort
Adam
am 8 Mai 2015
Bearbeitet: Adam
am 8 Mai 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.
0 Kommentare
Weitere Antworten (2)
CAM
am 8 Mai 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
Siehe auch
Kategorien
Mehr zu Workspace Variables and MAT-Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!