Assign values to a new variable via a function

조회 수: 10 (최근 30일)
Tatiana Bernard
Tatiana Bernard 2018년 12월 13일
댓글: Stephen23 2018년 12월 13일
I have a repetitve task that I want to turn into a function. The process that I am repeating at the moment for many variables is:
load('names_v1.mat')
names_v2 = names_v1;
save('names_v2','names_v2')
To turn this process into a function the bit I am struggling with is line two. That is in the below function the line namesNew = namesOld will obviously not work becuase namesOld is the string with the variable name and not the variable itself. I was trying to use the variableValues function but that doesn't seem appropriate
function test = fileRet(oldVersion, newVersion)
% old verion might be 'v1'
% new version might be 'v2'
namesOld = strcat('names_', oldVersion);
namesNew = strcat('names_', newVersion);
load(namesOld)
% Below line is the line that doesn't work
namesNew = namesOld;
save(namesNew,namesNew)
end
Any ideas
  댓글 수: 1
Stephen23
Stephen23 2018년 12월 13일
"...will obviously not work becuase namesOld is the string with the variable name and not the variable itself. I was trying to use the variableValues function but that doesn't seem appropriate"
Indeed, it is not appropriate at all.
"Any ideas"
Do NOT try to magically access variable names, unless you want to force yourself into writing slow, complex, buggy code that is hard to debug. Read this to know why:

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

채택된 답변

Stephen23
Stephen23 2018년 12월 13일
"% Below line is the line that doesn't work"
namesNew = namesOld;
It doesn't work because you are trying to magically access variable names using strings, which is certainly possible, but it is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
Writing better (simpler, more robust, less buggy) code makes this task easier. For example, you should always load a .mat file into an output variable (which is a structure):
S = load(...);
Working with fields of a structure is much easier than magically accessing variable names, so lets try that:
S = load(namesOld);
C = struct2cell(S);
T = cell2struct(C,namesNew,1);
save(namesNew,'-struct','T')

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 12월 13일
sprintf()
  댓글 수: 1
Tatiana Bernard
Tatiana Bernard 2018년 12월 13일
Thank you for the response and perhaps it was my explanation but I don't need to format data into a string. What i need is a way to set names_v? to be equal to the variable names_v? in a function. So I don't want to write names_v? because i want the version to be an input that can be changed. Creating the string names_v? is fine, it is setting up the new variable that is the issue.

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

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by