How do I pass a variable into a function without defining it as global or in the arguement?

23 views (last 30 days)
Hi, I'm writing a bit of code that will perform a nlinfit nine times. The code uses a function which is called each time I want to fit and the variable I need to pass in changes each time. How can I pass it in without defining it as global?
  3 Comments
Stephen23
Stephen23 on 27 Jul 2017
Edited: Stephen23 on 27 Jul 2017
"the variable I need to pass in changes each time"
Doing that will make your code slow and complex. Much simpler is to use MATLAB properly: put that data into one vector (it could be numeric/cell/struct/...) and loop over the elements of that vector: trivially easy!
Did you see what I just did there? I turned your slow and complex "problem" (accessing variables dynamically) into simple code by using good code practices (simple loops and indices). Read more here:
The name "MATLAB" comes from "MATrix LABoratory", and not from "Lets put all of our data into separate variables and make processing them really slow and complex". Because MATLAB processes matrices and arrays so efficiently (that is what it was written to do: see the name) this is how you should write your code: by putting the data into one array.
Although passing an argument will be be far the simplest and most efficient way of doing this, you might want to read about all of the possible ways to pass data between workspaces:
and also how to parametrize function calls using anonymous functions:
matlabkid602
matlabkid602 on 27 Jul 2017
Okay thanks for the information Cobeldick. I did have a laugh at your enthusiasm for indexing matrices.

Sign in to comment.

Accepted Answer

Jan
Jan on 27 Jul 2017

More Answers (1)

Steven Lord
Steven Lord on 27 Jul 2017
Do you mean that you need to pass an additional function into the function handle you specify as the modelfun input in your call to nlinfit? If so, use one of the techniques described on this documentation page.

Tags

No tags entered yet.

Products

Community Treasure Hunt

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

Start Hunting!