# How to turn a subroutine into a function?

I've written a subroutine that takes in 6 matrices and after some manipulation returns back 3 new ones.

I will use this subroutine fairly often in this notebook so I think it would be easier to turn the whole process into a function M[matrix1, matrix2, matrix3, matrix4, matrix5, matrix6]. Is there a way to do this?

Clear[data1P, data1N, data2P, data2N, data3P, data3N, i]
data1P = matrixIN1;
data2P = matrixIN2;
data3P = matrixIN3;
data1N = matrixIN4;
data2N = matrixIN5;
data3N = matrixIN6;

For[i = 1, i <= Length[data2P], i++,
AppendTo[data1P, data2P[[i]]];
AppendTo[data1N, data2N[[i]]];
]

For[i = 1, i <= Length[data3P], i++,
AppendTo[data1P, data3P[[i]]];
AppendTo[data1N, data3N[[i]]];
]

matrixOUT1 = data1P;
matrixOUT2= data1N;

matrixOUTp3 =
matrixOUT1[[All, 2]] -
matrixOUT2[[All, 2]];

matrixOUT3 =
Table[{matrixOUT1[[i,1]], matrixOUTp3[[i]]}, {i, 1,
Length[matrixOUTp3]}];

• ...and where is this "subroutine" you speak of? Hard to recommend anything without seeing it. – J. M. will be back soon Apr 8 '16 at 12:31
• @J.M. Let me recommend a Module though :) – Kuba Apr 8 '16 at 12:33
• @Kuba, it depends; you sometimes can get away without a scoping construct, at the cost of deep nesting. ;) – J. M. will be back soon Apr 8 '16 at 12:35
• Instead of using AppendTo[], have you looked into using Join[]? – J. M. will be back soon Apr 8 '16 at 12:49
• I will now. Thank you. – Gabu Apr 8 '16 at 12:50

Here is the code converted to function + some corrections:

function[arrays : {__?ArrayQ}] := Module[{
temp1, temp2, temp3
},
temp1 = Join @@ arrays[[{1, 2}]];
temp2 = Join @@ arrays[[{4, 5}]];

temp3 = Transpose[{
temp1[[;; , 1]],
temp1[[;; , 2]] - temp2[[;; 2]]
}];

{temp1, temp2, temp3}

]


There is no check if appropriate matrices are of the same length but your code doesn't contain any either.