0
$\begingroup$

This example code:

f[A_, B_] := Eigensystem[{{A, B}, {A + B, A - B}}] CodeBlock := {A = Ain; B = Bin; f[A, B]} With[{Ain = 1, Bin = 2}, CodeBlock] With[{Ain = 1, Bin = 2}, Evaluate[CodeBlock]] 

gives this output:

{{{1/2 (2 Ain - Bin - Sqrt[Bin] Sqrt[4 Ain + 5 Bin]), 1/2 (2 Ain - Bin + Sqrt[Bin] Sqrt[4 Ain + 5 Bin])}, {{-((-Bin + Sqrt[Bin] Sqrt[4 Ain + 5 Bin])/(2 (Ain + Bin))), 1}, {-((-Bin - Sqrt[Bin] Sqrt[4 Ain + 5 Bin])/(2 (Ain + Bin))), 1}}}} {{{-Sqrt[7], Sqrt[7]}, {{1/6 (2 - 2 Sqrt[7]), 1}, {1/6 (2 + 2 Sqrt[7]), 1}}}} 

This shows that, firstly Eigensystem does the symbolic calculation, then the local values of With is plugged into the result expression. This can be slow when the matrix is large. I want the local values to be "eagerly" plugged so Eigensystem will go the numerical way. How to realize that?

Maybe my coding style of using a code block is bad, which leads to this problem. What is a good style then that can solve this and meanwhile still have the similar convenience of calling a large block of codes?

This issue is not just with With, but also all the other local-variable functions like Manipulate. I am not sure whether functions like Table have this issue too, since the result expression always gets evaluated.

$\endgroup$
4
  • 1
    $\begingroup$ I believe you want Block rather than With. For instance, Block[{A = 1, B = 2}, f[A, B]]. If you Trace the evaluation, you will see that the numbers get plugged in before it finds the Eigensystem. Of course, it's still doing it symbolically. To force it do it numerically, do A = 1., for instance. I think you can also do f[A = 1, B = 2] if you would like to simultaneously set the values of A and B. As for the rest of the stuff, I'm not sure. $\endgroup$ Commented Sep 21, 2015 at 17:13
  • $\begingroup$ @march Great! Now I see the difference. Thanks. $\endgroup$ Commented Sep 21, 2015 at 17:20
  • 4
    $\begingroup$ Definitely check out What are the use cases for different scoping constructs?. $\endgroup$ Commented Sep 21, 2015 at 17:57
  • 1
    $\begingroup$ By the way: it's preferable not to start your variable and function names with an uppercase letter to avoid conflicts with built in names. Your Bin is already dangerously close to such a conflict. $\endgroup$ Commented Sep 21, 2015 at 18:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.