So I'm trying to write a recursion module in Mathematica (specifically for strassen multiplication but this doesn't matter). My issue is I don't really know how If statements work in Mathematica and if I can program recursive functions in the same way as I once learned in Java.
My (incomplete) code is
Strassen[A_, B_, p_] :=
Module[
{A11, A12, A21, A22, B11, B12, B21, B22, Return,
originalDim = Dimensions[A][[1]], dim, extraDim, cutoff = 40,
PaddedA, PaddedB},
//IMPORTANT STUFF
If[originalDim <= cutoff,
Return = mm[A, B, p]
];
//IMPORTANT STUFF
//UNIMPORTANT STUFF
dim = If[NumberIsPowerOfTwo[originalDim], originalDim,
MinimalPowerOfTwo[originalDim]];
PaddedA = PadRight[A, {Automatic, dim}];
PaddedA = PadRight[Transpose[PaddedA], {Automatic, dim}];
PaddedB = PadRight[B, {Automatic, dim}];
PaddedB = PadRight[Transpose[PaddedB], {Automatic, dim}];
A11 = PaddedA[[1 ;; dim/2, 1 ;; dim/2]];
A12 = PaddedA[[dim/2 + 1 ;; dim, 1 ;; dim/2]];
A21 = PaddedA[[1 ;; dim/2, dim/2 + 1 ;; dim]];
A22 = PaddedA[[dim/2 + 1 ;; dim, dim/2 + 1 ;; dim]];
B11 = PaddedB[[1 ;; dim/2, 1 ;; dim/2]];
B12 = PaddedB[[dim/2 + 1 ;; dim, 1 ;; dim/2]];
B21 = PaddedB[[1 ;; dim/2, dim/2 + 1 ;; dim]];
B22 = PaddedB[[dim/2 + 1 ;; dim, dim/2 + 1 ;; dim]];
]
Now the point of my function is that at some point I will call it again to do some multiplications on smaller matrices. Eventually when my matrices are small enough I want them to enter the If-statement and return the value "Return", but before that I want it to just skip that part and execute the code below.
Is this how if statements work in Mathematica?
?Return. – bill s Dec 07 '15 at 21:23Returnconflicts with a built in. – george2079 Dec 07 '15 at 21:24Good point about Return, will change that
– Sertii Dec 07 '15 at 21:24Ifstatement isn't the problem. (In fact, you need it.) RemoveReturnfrom the list of variables, and change theIfstatement toIf[originalDim <= cutoff, Return[mm[A, B, p]]]. In addition, I am assuming that you want an output from this function even when theIfstatement is not satisfied. If I am right, what is that output supposed to be? – march Dec 07 '15 at 21:35Strassenthat will act as input for the recursive call ofStrassen, don't you? – march Dec 07 '15 at 21:37Ifyou can create separate functions and use pattern matching:Strassen[A_List /; Dimensions[A][[1]] < 40, B_, p_] := ..– george2079 Dec 07 '15 at 21:50