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

Things you should read about:

Module, Functions as Procedures tutorial, Part, Join, PatternTest


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.