# Mathematica tips

By Wolfgang Keller
Originally written 2024-04-27

Some beginner tips for using Mathematica.

## Expression to a string for inputting

Convert an expression to a string: TextString[expression] // InputForm where expression denotes the expression to convert. See

Remark (2024-06-01): Better use ToString[InputForm[expression]]? TextString[RootApproximant[1.41421356237, 2]] // InputForm returns "1.41421" while ToString[InputForm[RootApproximant[1.41421356237, 2]]] yields the expected "Sqrt[2]".

## Create a matrix of subscripted elements

Array[Subscript[a, #1, #2] &, {3, 3}] // MatrixForm

Code taken from Subscript: Place a character below the baseline—Wolfram Documentation [visited 2024-04-27T00:04:48Z]. See also

## Semidefinite Optimization

If you copy the code of the first example of SemidefiniteOptimization—Wolfram Language Documentation [visited 2024-04-26T22:42:27Z], you get

Subscript[a, 0] = ({
{0, 1},
{1, 0}
}); Subscript[a, 1] = ({
{1, 0},
{0, 0}
}); Subscript[a, 2] = \!$$\* TagBox[ RowBox[{"(", "", GridBox[{ {"0", "0"}, {"0", "1"} }, GridBoxAlignment->{"Columns" -> {{Center}}, "ColumnsIndexed" -> {}, "Rows" -> {{Baseline}}, "RowsIndexed" -> {}}, GridBoxSpacings->{"Columns" -> { Offset[0.27999999999999997], { Offset[0.7]}, Offset[0.27999999999999997]}, "ColumnsIndexed" -> {}, "Rows" -> { Offset[0.2], { Offset[0.4]}, Offset[0.2]}, "RowsIndexed" -> {}}], "", ")"}], Function[BoxForme, MatrixForm[BoxForme]]]$$;
res = SemidefiniteOptimization[2 Subscript[x, 1] + 3 Subscript[x, 2],
Subscript[a, 0] + Subscript[a, 1] Subscript[x, 1] +
Subscript[a, 2] Subscript[x, 2]
\!$$\*UnderscriptBox[\(\[VectorGreaterEqual]$$,
TemplateBox[{"2"},
"SemidefiniteConeList"]]\) 0, {Subscript[x, 1], Subscript[x, 2]}]

This code is confusing to read, and in particular gives barely any hint how to create the relation for a matrix being semidefinite ($$\underset{S^2_+}{\succeq}$$).

The following code considerably simplifies this example:

a0 = {{0, 1}, {1, 0}}; a1 = {{1, 0}, {0, 0}}; a2 = {{0, 0}, {0, 1}};
res = SemidefiniteOptimization[2 x1 + 3 x2,
VectorGreaterEqual[{a0 + a1 x1 + a2   x2, 0}, {"SemidefiniteCone", 2}],
{x1, x2}]

Note that you can also use Minimize if you want an exact result:

a0 = {{0, 1}, {1, 0}}; a1 = {{1, 0}, {0, 0}}; a2 = {{0, 0}, {0, 1}};
res = Minimize[2 x1 + 3 x2,
VectorGreaterEqual[{a0 + a1 x1 + a2 x2, 0}, {"SemidefiniteCone", 2}],
{x1, x2}]

Concerning creating the semidefinite partial ordering via VectorGreaterEqual, see VectorGreaterEqual—Wolfram Language Documentation [visited 2024-04-27T00:22:25Z].`