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.
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!