Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

very simple one - return variables

Status
Not open for further replies.

suigeneris

Computer
Apr 23, 2003
8
DE
Hi,
I just started programming MatLab, so I still have basic problems.

I have 3 M-Files. One script which operates the two other function m-files and the two function m-files which seperate functions. In the first m- file I get a variable X in the end. But I don't save the variable. In the second m-file which I access after the first one I need X. I though I can just address X but then I get an error.

How can the second function adress the variable X without saving it.

greets

sui
 
Replies continue below

Recommended for you

if function 1 is defined as
Code:
function x = SomeFunction1(a,b,c,d)
   
  x = a+b+c+d

and function 2 is defined as

Code:
function y = SomeFunction2(e,f,g,p)
   
  y = e*f*g*p

Then the code in the main script would be

Code:
TotalFood = SomeFunction1(Apples,Bananas,Carrots,Dessert)

TotalCalories = SomeFunction2(Meals,Days,People,TotalFood)

The only variable in the first function which is avaiable to the main program is "y" which has been given the name "TotalFood" in the main program. If you want to pass more than one variable back from a function into the main workspace then you have to specify it in the function definition eg
Code:
function [x,y,z] = SomeFunction3(a,b,c)
   x = b+c;
   y = a*b;
   z = c/a;
and in the main program
Code:
[p,q,r] = SomeFunction3(NumberOfMice,NumberOfCats,NumberOfDogs);
The variables in the function SomeFunction3 with the lables x, y and z are now available in the main workspace with the lables p, q and r.

If you have a particular variable (or more usually a constant) which you want to be available to all functions you can use the "global" command. Type "help global" for more info.

M
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top