How do I access a base workspace variable from within a MATLAB function?

조회 수: 111 (최근 30일)
I want to change the values of variables in the base workspace, from inside a MATLAB function. For example, I have a function 'myfcn'. It accepts strings as input, which contain the names of variables that exist in the base workspace. I want to change the values of these variables in the base workspace, without having to pass them as output from the function.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2023년 6월 15일
편집: MathWorks Support Team 2023년 6월 15일
The EVALIN function allows you to evaluate commands in two specified workspaces: 'base' (MATLAB's base workspace), and 'caller' (the workspace where the function was called from). In the case where the function was called from the base workspace, the two workspaces are the same. You will need to create a string that will evaluate as the proper MATLAB expression, in order to perform the assignment.
Example using EVALIN:
function myfcn(varname)
for i = 1:size(varname,1)
if iscellstr(varname),
evalin('base',[varname{i} ' = 'mat2str(i) ';'])
elseif ischar(varname)
evalin('base',[deblank(varname(i,:)) ' = 'mat2str(i) ';'])
end
end
The ASSIGNIN function assigns values to variables in the same specified workspaces. This allows you to avoid the string conversion which is necessary with EVALIN.
Example using ASSIGNIN:
function myfcn(varname)
for i = 1:size(varname,1)
if iscellstr(varname),
assignin('base',varname{i},i)
elseif ischar(varname)
assignin('base',deblank(varname(i,:)),i)
end
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 4월 23일
@Tong Zhao No, that is not true.
lives_in_base = 1;
function_that_uses_evalin();
Upon call, function_that_uses_evalin reports lives_in_base = 1 function_that_uses_evalin tried using evalin to change lives_in_base to 2 after attempt to change, function_that_uses_evalin reports lives_in_base = 2
fprintf('after function_that_use_evalin terminates, back in base, lives_in_base = %g\n', lives_in_base);
after function_that_use_evalin terminates, back in base, lives_in_base = 2
function function_that_uses_evalin
oldv = evalin('caller', 'lives_in_base');
fprintf('Upon call, function_that_uses_evalin reports lives_in_base = %g\n', oldv);
evalin('caller', 'lives_in_base = 2;')
fprintf('function_that_uses_evalin tried using evalin to change lives_in_base to 2\n')
newv = evalin('caller', 'lives_in_base');
fprintf('after attempt to change, function_that_uses_evalin reports lives_in_base = %g\n', newv);
end

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by