How can I efficiently pass variables from an m-file to a function in MATLAB?

  • Thread starter Thread starter andrew.c
  • Start date Start date
  • Tags Tags
    Matlab Variables
Click For Summary
SUMMARY

The discussion focuses on efficiently passing variables from an m-file to a function in MATLAB. Users are advised against using global variables due to inefficiency. Instead, the correct approach involves calling the function directly from the main m-file, ensuring that the function is defined in a separate file (e.g., "shift.m"). Variables are passed by value, similar to C programming, which is a key aspect of MATLAB's function handling.

PREREQUISITES
  • Understanding of MATLAB function syntax
  • Familiarity with m-files in MATLAB
  • Knowledge of variable scope in programming
  • Basic programming concepts, particularly in C
NEXT STEPS
  • Review MATLAB function creation and file organization
  • Explore variable scope and passing mechanisms in MATLAB
  • Learn about MATLAB's memory management and performance optimization
  • Study the differences between passing by value and passing by reference in programming
USEFUL FOR

MATLAB users, software developers, and anyone looking to improve their understanding of function variable handling in MATLAB.

andrew.c
Messages
46
Reaction score
0
Hiya,

I have been trying for hours to figure out how to pass a variable from an m-file to a function,

i could get it to work by making the variables global, but I've beeen told this is inefficient.

Any ideas?
Cheers!
 
Physics news on Phys.org
Take a look at this Matlab tutorial, especially section 4-22. http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/getstart.pdf
 
Perhaps I am misunderstanding the question, but you call the function in your main ".m" file (script).
Assuming your function name is "shift(input1, input2)", then it should be stored in "shift.m", (as it is a function, and they are typically stored in separate files). You call it appropriately with the correct function syntax. Remember in Matlab, you are passing copies of the variables into the function, like you would in C.
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
3
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K