How to save variables in MATLAB function in the workspace

123 visualizaciones (últimos 30 días)
Good day.
I have a MATLAB function which I run from a script. I want to plot some variables in the function from my script so I want to save these variables in my workspace. Is there any way to do it other than using them as an output to the function when I call it from the script? The variables are many so I am trying to avoid too many output arguments.
Thanks now and always.
  1 comentario
Stephen23
Stephen23 el 29 de Mayo de 2020
Messing around with assignin or lots of output variables is not a good approach.
Just assign the variables to fields of a structure and return that. Simple.

Iniciar sesión para comentar.

Respuesta aceptada

Robin Kirsch
Robin Kirsch el 29 de Mayo de 2020
Use assignin command
function y = test()
assignin('base','x',42)
y = 0
end
  4 comentarios
Robin Kirsch
Robin Kirsch el 29 de Mayo de 2020
the workspace can be empty and it will save it to it
Robin Kirsch
Robin Kirsch el 29 de Mayo de 2020
this works only if you run your function first and then run your script to plot the variables of course

Iniciar sesión para comentar.

Más respuestas (1)

Cris LaPierre
Cris LaPierre el 29 de Mayo de 2020
You could save them to a mat file. When you want to plot them, load the mat file in your script.
You could also consider placing the variables in a structure. That way, your function only needs to have one output, yet all the variables can be passed out.
  9 comentarios
Cris LaPierre
Cris LaPierre el 1 de Jun. de 2020
Just to clarify, that wasn't Stephen's suggestion. His recommendation was NOT to do that. He suggested using a structure, as did I. That would likely be the quickest approach since you don't have to write the variables to the workspace or the harddrive.
ojonugwa adukwu
ojonugwa adukwu el 1 de Jun. de 2020
Sorry. I meant Robin Kirsch. The "assignin" he suggested is slow but it is faster than the process of saving to matfile. I really do not know why that has been extremely slow for me. Hopefully I will get to know why.
Thanks so much

Iniciar sesión para comentar.

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by