我想知道是否有可能从脚本中生成一个函数。为了澄清,我在Matlab中有计算商品季节性溢价的脚本。由于我有多个商品,所以我制作了多个脚本,每个脚本都有相同的季节性编码。
现在我想把季节性脚本转换成一个函数,以便有一个清晰的主程序!!(为了计算季节性,我不得不用200行)
季节性脚本的好处是,我只有一个输入矩阵,输出将是三个矩阵。
或者可以在脚本中执行不同的脚本而不复制每一行?
发布于 2014-05-26 13:05:59
参见函数文档,这里。下面是一个例子:
function yourOutput = Seasonality(yourInput)
yourOutput = yourInput + rand(); % Replace with your own code.
end为了清晰起见,这段代码被保存为一个单独的.m文件。要在主脚本中使用它,只需像使用任何其他函数一样使用Seasonality。如果还不清楚,请将您的代码作为编辑发布到您的问题上,我将查看它并告诉您该做什么。
发布于 2014-05-26 13:04:24
假设您有两个MATLAB脚本,如下所示:
x = 42
y = 43
% do some complicated calculations with x and y and display the result
% ...和
w = 1
z = 0
% do the calculations from the first script, but with the values w and z
% ...您可以简单地创建一个函数,它接受一些输入参数并返回一个结果。对于我们的简单例子,我们可以写:
function result = my_function(argument1, argument2)
% do some complicated calculations with argument1 and argumen2
% ...
% assign result of the computation to the variable result
end现在,您可以简单地使用任意两个输入值调用my_function。有关更多信息,请参考http://www.mathworks.de/de/help/matlab/ref/function.html -这也将解释如何返回多个结果值。
下面是关于您的功能将如何工作的快速草图:
function [M1 M2 M3] = my_function(input_argument)
% do some complicated calculations for M1, M2, M3 based on input_argument
% ...
% assign some bogus values to M1, M2, M3 for demonstration
M1 = [1, 2; 3, 4];
M2 = [5, 6, 7; 8, 9, 10];
M3 = [11, 12; 13, 14; 15, 16];
end在解释器中调用my_function将如下所示:
>> [M1 M2 M3] = my_function(42)
M1 =
1 2
3 4
M2 =
5 6 7
8 9 10
M3 =
11 12
13 14
15 16请注意,保存my_function的文件应该命名为my_function.m。
https://stackoverflow.com/questions/23870387
复制相似问题