MATLAB: How to run the script in matlab R2019

basicsr2019

I can't get my script to run in the newer matlab build. I'm being forced to use the newest version for this assignment. The issue is that the function part goes at the bottom of the script, so at the top of the script are my final result variables that I want it to display. These are undefined till after the code runs. When I try to run it, I get an error that these top variables are undefined, if I move these undefined varibles to the bottom of the script, it gives me the error that the function part must be at the bottom of the script. Out smarted by matlab, somebody please help me. I've included the basics of the code to show what I mean.
format long e
sum = f
abserr = y
relerr = y/e
n = i
function[tay]=taylor(x,n)
%code goes here
end

Best Answer

Your script is trying to access variables that only exist in the workspace of the function. The workspace of a function is destroyed after the function returns.
You have a couple of choices:
  • you can convert the function into a script in a different file
  • you can return those values from the function
  • you can define a nested function with shared variables
  • you can use assignin('base')
  • you can display the values directly in the taylor function
The nested function approach would look like:
format long e
x = 1.234;
n = 7;
outer_function(x, n)
function outer_function(x, n)
f = []; y = []; e = []; i = []; %all shared variables must be defined before the inner function
tay = taylor(x, n)
sum = f
abserr = y
relerr = y/e
n = i
function tay = taylor(x, n)
%code goes here
end
end