필터 지우기
필터 지우기

Rename a variable using a string

조회 수: 99 (최근 30일)
Calvin Ebert
Calvin Ebert 2019년 3월 22일
편집: Calvin Ebert 2019년 3월 25일
Ok ok, I see everyone says to not create dynamic variables and all but I am trying to do something specific, if there is another method, Ill gladly accept it.
I have some mat files saved with tables, all the same type just different "Machines" on each different file.
I want to use a function to do things with those tables and save them with the same name. Here is what I have:
function DoStuff(Name)
Name=strcat(Name, 'TheRestOfTheFileName')
load('Folder', Name) %This puts the variable in the workspace with its own name
NewVar=load('Folder', Name)
NewVar=NewVar.(Name) %This creates a new variable with the data from the old one.
I want it this way so I can do the same process to all of the files just by changing the name and running it through this function.
Now after running stuff, I want it to save to the same place with the same name
I was thinking about saving over the original variable since I can use save('Folder', Name) and I have tried assignin('base', Name, NewVar) with no luck.
Can anyone suggest a way to do this?
I am thinking since this function will be in another, I can just call the result from DoStuff, then manually set and save it. Hopefully works but would be good to know a method for this either way
Thank you very much

채택된 답변

Stephen23
Stephen23 2019년 3월 22일
편집: Stephen23 2019년 3월 22일
"Rename a variable using a string"
Why bother? Both load and save work with scalar structures, which makes your task easy:
S = load(filename)
V = S.(name)
... do stuff with V
S.(name) = V;
save(filename,'-struct',S)
Or skip assigning to V and just work with S.(name) directly. You might also find other load and save options useful (e.g. specifying fields to import/save): read the documentation carefully!
  댓글 수: 1
Calvin Ebert
Calvin Ebert 2019년 3월 25일
편집: Calvin Ebert 2019년 3월 25일
Beautiful, thank you for clearing that up for me! I will try it out.
Edit: Code working perfectly, thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by