user45266
user45266

Reputation: 25

from script to function

I was wondering if it is possible to make from a script a function.. To clarify, I have script in Matlab that calculate the seasonal premium of a commodity. As I have multiple commodities I made multiple scripts, where each script has the same coding for seasonality.

Now I want to transform the seasonality script into a function in order to have a clear mainscript!! (In order to calculate the seasonality, I had to use 200 lines)

The nice thing about the seasonality script is that I only have one input matrix and the output will be three matrices.

Or is it possible to execute a different script in a script without copying every line?

Upvotes: 1

Views: 84

Answers (2)

timgeb
timgeb

Reputation: 78690

Let's say you have two MATLAB scripts which look like this:

x = 42
y = 43

% do some complicated calculations with x and y and display the result
% ...

and

w = 1
z = 0

% do the calculations from the first script, but with the values w and z
% ...

you can simply create a function which accepts some input arguments and returns a result. For our simple example, we could write:

function result = my_function(argument1, argument2)
   % do some complicated calculations with argument1 and argumen2
   % ...
   % assign result of the computation to the variable result
end

Now you can simply call my_function with any two input values you desire. For more information please refer to http://www.mathworks.de/de/help/matlab/ref/function.html - this will also explain how to return multiple result values.

Here's a quick sketch on how your function would work:

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

Calling my_function in the interpreter would go like this:

>> [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

Please note that the file in which my_function is saved should be named my_function.m.

Upvotes: 0

Justin Fletcher
Justin Fletcher

Reputation: 2409

See the function documentation, here. Here's an example:

function yourOutput = Seasonality(yourInput)
    yourOutput = yourInput + rand();  % Replace with your own code.
end

This code an be saved as a separate .m file, for clarity. To use it in your main script, simply use Seasonality as you would any other function. If it's still unclear, post your code as an edit to your question, I will take a look at it and tell you what to do.

Upvotes: 1

Related Questions