How to replace variable names in a mat file
조회 수: 106 (최근 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
댓글 수: 0
채택된 답변
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.
댓글 수: 0
추가 답변 (2개)
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
참고 항목
카테고리
Help Center 및 File 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!