Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Assigning a variable in a function that is available in the function

조회 수: 1 (최근 30일)
William Mills
William Mills 2014년 10월 14일
마감: MATLAB Answer Bot 2021년 8월 20일
I have a function which creates variables (which I want to use in the function only) that are listed in a file that contain the actual variable name and the associated starting/default value. I have tried assign(ws, 'var', val) where 'var' and val come from the file. The problem is these are being assigned to he base ws (regardless if ws = 'base' or 'caller'). I thought I could use evalin but that function needs to know the name of the variable you want to assign it to and that name comes from the file.
  댓글 수: 3
William Mills
William Mills 2014년 10월 14일
It is written to read a user file that has override values on some of the variables. If there is an override value the function creates the variable named by the file and assigns the variable the data supplied by the user, otherwise the variable is created and is assigned a default value. I assignin was creating the variables ok and giving them the right values but it was in the base workspace and not in the functions.
So I think eval function might work... like this.. eval([MatchTableHead_General{2,i}(:,:),'= num(:,ColumnNo);']); where 'MatchTableHead_General contains the list of possible variable names, i = the one that the user has selected to override and 'num(:,columnNo) is the value supplied by the user I think this works.
Sean de Wolski
Sean de Wolski 2014년 10월 14일
That sounds really difficult. Can you provide an actually minimal working example. You should not use or need eval to do this.

답변 (2개)

Robert Cumming
Robert Cumming 2014년 10월 14일
Create a sub function which assigns (using assignin) your variables in the caller function where the caller function is the one where you actually want the variables.

Matt J
Matt J 2014년 10월 14일
편집: Matt J 2014년 10월 14일
Methods that avoid eval and assignin are preferable (by far) for this kind of thing. You should use load as Sean suggested, but with an output argument
defaults=load('YourFile.mat');
You should also have the user provide a similar structure whose fields are the overrides
override.var1=val1
override.var2=val2;
etc...
Now you just loop through the fields of "defaults" and replace with overrides as needed,
settings=defaults;
fnames=fieldnames(settings);
for i=1:length(fnames)
if isfield(overrides,fnames{i})
settings.(fnames{i})=overrides.(fnames{i});
end
end
The desired data are now all in the fields of the structure "settings". If you strongly prefer them unpacked into separate variables, you could do so with STRUCTVARS ( Download ).

제품

Community Treasure Hunt

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

Start Hunting!

Translated by