Stuart’s MATLAB Videos

Watch and Learn

Converting from a formula to a script to a function 10

Posted by Doug Hull,

Very often the process of coding in MATLAB is to start from a requirement, like “implement this formula”, to a script that is easily tested to a function that is more general and adds to the MATLAB language. This process is followed in simplified for for temperature conversions.

10 CommentsOldest to Newest

Claus replied on : 1 of 10
I am an experienced but incompetent MATLAB user and really appreciate these simple tutorials. I didn't learn anything new here but would like to hear more about functions within functions (e.g. what variables stay alive and which need to be passed on when one function calls another function)
dhull replied on : 2 of 10
@Claus, Thank you for the kind words. If I understand your question right, basically all variables need to be passed in and out of a function since they are destroyed once they leave scope of a function. Exceptions are made for persistent and global variables, but those are rare. Doug
name replied on : 3 of 10
Nice video. One related question - if I did want the value of "offset" to be stored in the workspace, but it is defined within the function code ... how could I do that? I guess one idea would be to make it an output argument, or alternatively I think one could use the evalin function, but I just thought I would ask if there is some other easier way. Thanks.
dhull replied on : 4 of 10
Can you clarify your question? You want "offset" to be stored in which workspace (the temporary function workspace or the base workspace that call the function) Doug
Stuart McGarrity replied on : 6 of 10
You include a function statement at the top:
Mike replied on : 7 of 10
I tried that. I get the error: Attempt to execute SCRIPT read_data as a function. This is in 2016a Matlab. Maybe Matlab keeps some private information that says it's a script?
Mike replied on : 8 of 10
Sorry, I was wrong. When I saved the script as function, it went into a different folder. It does work as you described.
khasa gillani khasa replied on : 9 of 10
hi, I am new to Matlab and just started to use it. so how can we map complex equations which taking expected values and variance of the variable to a script? and how to plot the graph based on results of equation.could you please give some guideline about that?
Stuart McGarrity replied on : 10 of 10
Hi Khasa, Can't you create a function and pass the expected value and variance in as parameters as Doug shows (~4:36)? What have you tried so far?