Printing a message inside a function

56 次查看(过去 30 天)
Hi everyone,
I'm new to using and creating my own functions, however, I'm having some trouble getting a simple message to print inside my function.
I want the function to run a script (file_name), which it does and I am happy with that. But I want that message (file1 'has finished running') to be displayed so that when I change this function to run say 3 other scripts, I will know when each have finished running.
So here I define the function:
function run_other_code()
global file1
file1 = fullfile(['path'],'file_name.m');
run(file1)
print([file1 'has finished running'])
end
And here is where I call it, in another script:
run_other_code()
It runs up to the print line, absolutely fine, and does the job of running the other script. But then it fails and I get the following error message:
Reference to a cleared variable file1.
Error in run_other_code (line 5)
print([file1 'has finished running'])
I just can't work out why it doesn't work, I made file1 a global variable as I thought perhaps it was getting lost after it has been used first.
But I'm just not sure how to fix it. If anyone could help that would be brilliant - thank you.

采纳的回答

Star Strider
Star Strider 2022-5-13
Use either:
sprintf('%s has finished running',file1)
or:
fprintf('\n%s has finished running\n',file1)
depending on the result you want.
See the documentation on fprintf (links to the other) for details.
  2 个评论
Shauna Smith
Shauna Smith 2022-5-13
Thanks so much for your answer, I really appreciate the help.
I tried just adding your answer to the end of my function, but it didn’t solve the problem.
I’ve realised that when my code runs the other script, the previous variables I had ie. file1, are getting cleared, and the variables created from the other script are replacing them.
This means that anything I write under ‘run(file1)’, won’t work as these variables have been cleared.
So, I realised I had to save my variables before the other script is run, then it run it, clear the new ones, and the then load in the old ones, and then add your fprintf line.
So problem solved!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by