PHY307F/407F - Computational Physics

A Common Kludge in the Exercise

In Exercise 5, many students had code like the following to calculate the value of the V matrix:


V[A_?MatrixQ] := 
	Module[ {alphai, vv},
		alphai = Sqrt[Apply[Plus,Transpose[(A)^2]]];
		vv = Abs[Det[A]]/(alphai[[1]]*alphai[[2]])
] /; (Length[A] == Length[ A[[1]] ])

The first problem with this is that it only works when A is a 2 by 2 matrix. We can generalise to arbitrary matrices by changing the code to:


V[A_?MatrixQ] := 
Module[ {alphai, vv},
	alphai = Sqrt[Apply[Plus,Transpose[(A)^2]]];
	vv = Abs[Det[A]]/Apply[Times, alphai]
] /; (Length[A] == Length[ A[[1]] ])

We can re-write the above as:


V[A_?MatrixQ] := 
Module[ {denom, vv},
	denom = Apply[Times,Sqrt[Apply[Plus,Transpose[(A)^2]]]];
	vv = Abs[Det[A]]/denom
] /; (Length[A] == Length[ A[[1]] ])

Note in the above that we are now calculating the denominator in the temporary variable denom.

Now, it should be fairly obvious that we don't need any temporary variables at all. This, in turn, means we don't need to use a Module construct either:


V[A_?MatrixQ] := 
	Abs[Det[A]]/Apply[
		Times,Sqrt[
			Apply[Plus,Transpose[(A)^2]]
		]
	]	/; (Length[A] == Length[ A[[1]] ])

David Harrison, October 1998.