views:

216

answers:

3

Suppose I have a list of Matrices saved in the variable G and apply the following operations:

top[g_] = Minors[g]
Diagonal[top /@ G] 

Minorsreturns a matrix where each element is the determinant with the (i,j) row/col deleted, and Diagonal returns a list of the diagonal elements of a matrix.

My question is on the evaluation of these commands - clearly I do not want all entries evaluated. Is Mathematica lazy in the sense that Diagonal is parsed first which only extracts the elements needed from Minors or is the minor matrix constructed and then its diagonal elements are pulled out?

This is a general question for lazy evaluation, however being new to Mathematica I would appreciate any tips on how to improve the syntax for the specific problem.

+1  A: 

Hi

It's late so only a short answer: investigate Hold[] and its relatives. With them you can implement lazy evaluating functions. Most intrinsic Mathematica functions are not lazy, a few are. In general, as a beginner, you should avoid modifying the behaviour of Mathematica's intrinsic functions, though it is very good fun to do so and can very easily make the entire system unusable.

Regards

Mark

High Performance Mark
When you get the chance, could you edit your question to provide an example (perhaps the particular one as stated)?. The Mathematica website, while filled with examples, didn't seem to do anything practical.
Hooked
+1  A: 

No mathematica is not lazy in general.

top/@G 

Will produce a matrix that Diagonal will operate on. Since Minors does not operate on individual elements of the matrix, what you are asking for is not, from my knowledge, just lazy evaluation either.

I think I have a solution for you though.

Clear[f];
Diagonal[Minors[G,Length[G],f]]/.f->Det

This solution will only produce the Minors of the Diagonal elements to be summed by Diagonal. But I have only moved the excess computation to an excess memory usage problem. Since the submatrix of off diagonal elements is still produced only to be thrown away. I will post again if I think of a way to prevent that as well.

Davorak
+2  A: 

You can solve this problem by building up the list of diagonal minors by yourself and then applying Det, for a matrix M:

Map[Det,Drop[Transpose[Drop[M,{#}]],{#}]& /@ Range[1,Dimensions[M][[1]]]]

This is a bit of a cludge but it is about 50 times faster than using Mathematica's built in Minors and picking off just the diagonal elements (tested on 100x100 random matrices).

Timo
(+1) For the practical solution to the particular problem (thank you!). I am selecting a different answer since the question was about lazy evaluation in Mathematica.
Hooked
No problem :-).
Timo