how to call a function one m-file to another m-file

1 view (last 30 days)
lets say i have one m-file named call1.m having:
function t =call1(a,b)
a=10;
b=5;
t=a+b;
end
and i want to call and run this function 't' in another m-file named call2.m, i wrote it as:
function call2()
t = @call1
end
but nothing happens please guide me.
Thanks

Answers (1)

Star Strider
Star Strider on 29 Oct 2015
You only need the ‘@’ operator (creating a function handle) if you are using the function as an input argument to another function. You are not here, so do this instead:
function call2()
t = call1
end
  1 Comment
Steven Lord
Steven Lord on 29 Oct 2015
Star Strider's suggestion will work because of the way your call1 function is written. The line that declares call1 tells MATLAB that it accepts up to 2 input arguments. Star Strider's code calls it with 0, and that works, because call1 completely ignores what you pass into it and overwrites those variables with hard-coded data.
If you eliminate the lines in call1 that assign values to a and b, then you could do this using a slightly modified version of Star Strider's code:
function call2()
t = call1(10, 5)
end
If you want to DO anything with that result, though, you probably want to define call2 in such a way that it returns the variable t to its caller.
function t = call2()
t = call1(10, 5);
end

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!