×
INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

very simple one - return variables

very simple one - return variables

very simple one - return variables

(OP)
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

RE: very simple one - return variables

if function 1 is defined as

function x = SomeFunction1(a,b,c,d)
   
  x = a+b+c+d


and function 2 is defined as


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


Then the code in the main script would be


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

function [x,y,z] = SomeFunction3(a,b,c)
   x = b+c;
   y = a*b;
   z = c/a;

and in the main program

[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

RE: very simple one - return variables

(OP)
Thank you very much. That helped a lot.

Greetings

sui

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Eng-Tips forums is a member-only feature.

Click Here to join Eng-Tips and talk with other members!


Resources