0
     clear[a];
    a = List[{0, 1, 2}, {1, 2, 3}, {2, 3, 4}]
    a // MatrixForm;
M2 = Transpose[a] // MatrixForm;
a + M2

I am trying to run this code for summation of two matrix. But finding difficulty to get simple output. In mathmatica it is in longer way and taking the whole matrix.

vijay
  • 3
  • 3

1 Answers1

1

Firstly let's try to understand what is MatrixForm.

There are a lot of "forms" that you can represent your data, as the documentation states: print with the elements arranged in a specific form. To get those: ?*Form. Now, XXXForm prints your data in a specific form, thus, it is not making an object itself. In Mathematica there is nothing like matrix, there are lists, and if your list is an array then it is a matrix, if it is rectangular array, then it is a rectangular matrix, so force, so on.

All that said, your code should be:

ClearAll[l];
l = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
lT = Transpose[l];
l + lT

You should try to "automize" your code as much as possible, for this particular case you can use functions:

ClearAll[matrixSum];
matrixSum[m1_, m2_] := Sum[m1, m2]

Since there are restrictions on matrics summation, you can preserve the validation:

ClearAll[matrixSum]
matrixSum[m1_ /; ArrayQ[m1, 2, Internal`RealValuedNumericQ], m2_/; ArrayQ[m2, 2, Internal`RealValuedNumericQ]] := m1 + m2 /;Dimensions[m1] === Dimensions[m2]

To make this even more accurate:

ClearAll[matrixSum];

mutrixSum::argx = "`1` and `2` matrices cannot be summed.";
mutrixSum::argx1 = "Two matrices are requred to be summed";
mutrixSum::argx2 = "No matrices given to be be summed.";
mutrixSum::argx3 = "Only two matrices are allowed as input.";

matrixSum[m1_ /; ArrayQ[m1, 2, Internal`RealValuedNumericQ], m2_/; ArrayQ[m2, 2, Internal`RealValuedNumericQ]] := m1 + m2 /;Dimensions[m1] === Dimensions[m2]

(* Overloads for failures *)
matrixSum[m1_, m2_]:= (Message[mutrixSum::argx,m1, m2]; Return[$Failed])
matrixSum[m1_]:= (Message[mutrixSum::argx1,m1]; Return[$Failed])
matrixSum[]:= (Message[mutrixSum::argx2]; Return[$Failed])
matrixSum[___]:= (Message[mutrixSum::argx3]; Return[$Failed])

You can also preserve the case for multiple matrix summations:

ClearAll[mutrixSum];

mutrixSum::argx = "All input matrices have to have the same dimensions and be rectangular.";
mutrixSum::argx1 = "At least two matrices are required to be summed";

mutrixSum[args__] := mutrixSum[List[args]]
mutrixSum[args_List?ListQ] := Plus @@ args /; AllTrue[Append[ArrayQ[#, 2, Internal`RealValuedNumericQ] & /@ args, SameQ @@ Dimensions /@ args], TrueQ]

(* Overloads for failures *)
mutrixSum[args_List?ListQ] := (Message[mutrixSum::argx]; Return[$Failed])
mutrixSum[arg_] := (Message[mutrixSum::argx1]; Return[$Failed])
mutrixSum[] := (Message[mutrixSum::argx1]; Return[$Failed])
SuTron
  • 1,708
  • 1
  • 11
  • 21