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

1 次查看(过去 30 天)
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

回答(1 个)

Star Strider
Star Strider 2015-10-29
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 个评论
Steven Lord
Steven Lord 2015-10-29
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

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by