Filter löschen
Filter löschen

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

19 Ansichten (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 27 Jul. 2017
Bearbeitet: Stephen23 am 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 am 27 Jul. 2017
Okay thanks for the information Cobeldick. I did have a laugh at your enthusiasm for indexing matrices.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 27 Jul. 2017

Weitere Antworten (1)

Steven Lord
Steven Lord am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by