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

19 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2017-7-27
编辑:Stephen23 2017-7-27
"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:

请先登录,再进行评论。

采纳的回答

Jan
Jan 2017-7-27

更多回答(1 个)

Steven Lord
Steven Lord 2017-7-27
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

尚未输入任何标签。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by