如何重用部分代码? (MATLAB)

时间:2014-10-15 16:27:16

标签: matlab

最近我写了一个使用理想气体定律的基本脚本。我设法使脚本工作正常,但它看起来非常笨重和不优雅,我想知道是否有更好的写作方式。该程序需要来自用户的2个输入,这是获取输入的代码部分。

x = input('Are you going to enter a [t]emperaute, a [p]ressure or a [v]olume?\n','s');

while(double(x) ~= double('t') && double(x) ~= double('p') && double(x) ~= double('v'))
% stop the user from entering anything but t,v or p
x = input('Please enter either t (for temperaure), p (for pressure) or v (for volume)\n', 's');
end  

if (double(x) == double('t')) 
T = input('OK, please tell me the temperature in Kelvin\n');
% Get the temperature value from the user
while (T <= 0) % negative temperatures aren't allowed
  T = input('Please enter a positive value for the temperature\n');
end
elseif (double(x) == double('p'))
P = input('OK, please tell me the pressure in Pascals\n'); 
% Get the pressure value from the user
while (P <= 0) % negative presures arent allowed
  P = input('Please enter a positive value for the pressure\n');
end
elseif(double(x) == double('v'))
V = input('OK, please tell me the volume in m^3\n');
% Get the volume value from the user 
 while (V <= 0) % Don't allow the user to enter negative or zero values for the volume
  V = input('Please enter a positive value for the volume\n');
 end      
end  

我认为这看起来有点愚蠢,if语句看起来非常相似。当我写这篇文章时,我只是复制粘贴条件并改变几句话。

当我必须从用户那里得到另一个变量时,在脚本中更糟糕的是,我只是粘贴完全相同的代码,将变量更改为y并在结尾处粘贴while (double(x) == double(y))条件以停止用户输入两次相同的输入。

有没有办法在MATLAB中重用部分代码?我试图为上面的大块代码定义一个函数,但MATLAB一直抱怨,因为我没有指定任何变量通过这个功能。

我确信会有一个基本的编程工作,但我是编程的新手(在MATLAB和一般情况下)。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

我认为这很容易做到:

http://www.mathworks.co.uk/help/matlab/matlab_prog/local-functions.html

您需要做的就是创建链接中显示的本地函数。毕竟你所做的就是提示并检查收到的值是否低于0.

之后,将第一个输入与集合进行比较,以使用地图容器为您提供正确的提示值:

http://www.mathworks.co.uk/help/matlab/map-containers.html?s_tid=doc_12b

所以你可以使用类似的东西:

function X = foo(x)

keySet =   {'t', 'p', 'v'};
valueSet = ['Kelvin', 'Pascal', 'm^3'];
units = containers.Map(keySet,valueSet)
X = input('OK, please tell me the temperature in'+ units(x) +'\n');
% Get the value from the user
while (X <= 0)
X = input('Please enter a positive value for the value \n');

end

然后你只需要调用函数:

温度= foo('t')

浏览我发布的链接。他们提供了一个好的起点。

P.S。我不相信那些输入提示,我不记得字符串在Matlab中如何工作,但要点应该是正确的。

P.P.S。您还可能想要添加一个检查,表明已将好的值传递给函数。

相关问题