Why is MATLAB code excution in a function not in a sequence like in the main script?

조회 수: 2 (최근 30일)
So here is the example:
% I run the initparameter file first
% the file contains a rigidbodytree object called robot
% Then define results = robot, it works fine
run('InitParameters.m');
results=robot;
% However, if I put this into a function
% The 'initparameter' file is not excuted first.
% This gives me an error indicating that robot is not found.
% The 'initparameter' file is not executed at all.
result=myfun();
function results=myfun()
run('InitParameters.m');
results=robot;
end
So is there a way to have the code run in sequence in a function just like in the main script? Maybe there is a duplicate to this question, but I can't seem to describe this properly... Please excuse me.
  댓글 수: 7
Yi Wan
Yi Wan 2018년 10월 22일
@Kevin, Unfortunately, the same error still occurs.
However, you mentioned 'interaction' which enlightened me. I tried inserting a break point at 'result=robot'. The first line (InitParameter) does execute. However, as soon as I jump to the second line, all the 'base' workspace variables are cleared. So I think it's more of a function scope problem.
That may be also why when the two lines are excuted in the global scope, it doesn't have that issue.
I'll try again with some other methods. Thanks for the advice anyway!
Kevin Chng
Kevin Chng 2018년 10월 22일
How about this?
result=myfun();
function results=myfun()
robot = [];
InitParameters;
results=robot;
end

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

채택된 답변

Walter Roberson
Walter Roberson 2018년 10월 22일
run() is a function that determines which file is being invoked and then does an evalin('caller') of the file.
When the script being executed is executed from the command line, the 'caller' will be the base workspace, and any assignin('base') that are executed will result in variables that are directly available to the calling environment because the calling environment is also the base workspace.
When the script being executed is executed from a function, the 'caller' will be the function that run was called from, and any assignin('base') that are executed would result in variables that are in the base workspace but not in the workspace of the function.
The easiest fix for this direct issue would be
function results=myfun()
InitParameters;
results = evalin('base', 'robot');
end
  댓글 수: 4
Walter Roberson
Walter Roberson 2018년 10월 22일
Run does itself deliberately assign values in the base workspace, but the script being executed might.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by