Why is MATLAB code excution in a function not in a sequence like in the main script?
Show older comments
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 Comments
Kevin Chng
on 22 Oct 2018
Hi,
Is your function file in the same path with your InitParameters.m?
Best solution is to specific the full path name for InitParameters.m
run('C:\Users\7.0 Community Question\14 reshape\InitParameters.m')
Yi Wan
on 22 Oct 2018
Walter Roberson
on 22 Oct 2018
InitParameters.m might be deliberately assigning values in the 'base' workspace.
Yi Wan
on 22 Oct 2018
Kevin Chng
on 22 Oct 2018
Edited: Kevin Chng
on 22 Oct 2018
First, to clarify your doubt about MATLAB function doesn't execute codes line by line
It is not possible. It is fundamental of programming to execute line by line. No doubt on that.
Use run to run script in function
It is very interesting to know that this way is not working. It is also my first time to see it.
Why?
For sure, it will run the script, but it is not interact with your function and also your MATLAB.
As you mentioned, there are not enough parameters, therefore it should return error in your MATLAB. But it did't. Interesting, it is run but not interact with your MATLAB and your function.
Any variable in the script won't be stored in your workspace and within your function. There is no interaction. I don't have good explanation for it, probably we may need to seek advice from MathWorks or expert here.
How to solve it? Don't use run. Just call the script as what majority people will do.
result=myfun();
function results=myfun()
InitParameters;
results=robot;
end
Yi Wan
on 22 Oct 2018
Kevin Chng
on 22 Oct 2018
How about this?
result=myfun();
function results=myfun()
robot = [];
InitParameters;
results=robot;
end
Accepted Answer
More Answers (0)
Categories
Find more on Robotics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!