Printing a message inside a function

97 visualizaciones (últimos 30 días)
Shauna Smith
Shauna Smith el 13 de Mayo de 2022
Comentada: Star Strider el 13 de Mayo de 2022
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.

Respuesta aceptada

Star Strider
Star Strider el 13 de Mayo de 2022
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 comentarios
Shauna Smith
Shauna Smith el 13 de Mayo de 2022
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!
Star Strider
Star Strider el 13 de Mayo de 2022
As always, my pleasure!

Iniciar sesión para comentar.

Más respuestas (0)

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by