How do I pass a variable into a function without defining it as global or in the arguement?
    27 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    matlabkid602
 el 27 de Jul. de 2017
  
    
    
    
    
    Comentada: matlabkid602
 el 28 de Jul. de 2017
            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 comentarios
  Stephen23
      
      
 el 27 de Jul. de 2017
				
      Editada: Stephen23
      
      
 el 27 de Jul. de 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:
Respuesta aceptada
Más respuestas (1)
  Steven Lord
    
      
 el 27 de Jul. de 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.
0 comentarios
Ver también
Categorías
				Más información sobre Logical en Help Center y File Exchange.
			
	Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




