Defining inputs for subfunctions

3 次查看(过去 30 天)
Hey,
I'm writing some code that involves using set inputs (that I want to be able to change easily) in multiple subfunctions.
Take the following example;
function [ output_args ] = Untitled2( input_args )
clc;
x=0:0.01:5;
plot(f(x),x,g(x),x)
end
function [f_value]=f(x)
speed=6;
f_value=0.5.*speed.*x;
end
function [g_value]=g(x)
speed=6;
g_value=(x.^2)./speed;
end
How would I go about being able to define speed only once and it being 'called up' by any and every subfunction that uses it? I tried looking into nesting but got utterly confused :/ Is there a simple way to do this?

采纳的回答

Walter Roberson
Walter Roberson 2011-12-8
function [ output_args ] = Untitled2( input_args )
speed = 6;
function [f_value]=f(x)
f_value=0.5.*speed.*x;
end
function [g_value]=g(x)
g_value=(x.^2)./speed;
end
x=0:0.01:5;
plot(f(x),x,g(x),x)
end
  3 个评论
Walter Roberson
Walter Roberson 2011-12-8
Yes. But it is important that the variable to be shared be defined before you define the nested functions that use the variable.
Stephen
Stephen 2011-12-8
Haha, yeah I'd literally just found that. Was trying to impliment it in my own code and was getting very confused why it wouldn't run as I couldn't see anything wrong with it. Then I had a brainwave and moved my variable to the start of my code and it worked a treat :)
Thank you very much for the help :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by