I have a list of expressions that operate on data.
Min[data]
Max[data]
Covariance[data, data1]
Mea开发者_运维百科n[data]
GeometricMean[data]
Total[data]
Sum[Log[data[[i]]], {i, 1, Length[data]}]
Sum[(data[[i]])^2, {i, 1, Length[data]}]
The output looks like this
Out[1]= 1.9
Out[2]= 3.1
....
Is it possible to show the result along with its expression? For example
Min[data] = 1.9
Max[data] = 3.1
....
Any advice on how to format that kind of output for easy reading is welcome!
You could use
$PrePrint =
Function[a,
Row[{ToExpression[InString[$Line], StandardForm, HoldForm], " = ",
a}]];
which is fine for small inputs, but perhaps not what you want for multiline inputs.
(You can turn this off again with Unset[$PrePrint]
)
data = {1, 2, 3, 4};
data1 = {2, 1, 4, 3};
ClearAll[exprShowAndEvaluate];
SetAttributes[exprShowAndEvaluate, {HoldAll, Listable}];
exprShowAndEvaluate[expr_] := Print[HoldForm[expr], "=", expr];
exprShowAndEvaluate[{Min[data],
Max[data],
Covariance[data, data1],
Mean[data],
GeometricMean[data],
Total[data],
Sum[Log[data[[i]]], {i, 1, Length[data]}],
Sum[(data[[i]])^2, {i, 1, Length[data]}]}];
(* output ==>
*)
Update
In his comment below Usavich, indicated he wants to pass a list of these expressions assigned to a variable to the function. This is not directly possible as the expressions evaluate in the process:
expr =
{
Min[data], Max[data], Covariance[data, data1], Mean[data],
GeometricMean[data], Total[data],
Sum[Log[data[[i]]], {i, 1, Length[data]}],
Sum[(data[[i]])^2, {i, 1, Length[data]}]
}
(* Output ==>
{1, 4, 1, 5/2, 2^(3/4) 3^(1/4), 10, Log[2] + Log[3] + Log[4], 30}
*)
You have to Hold
the expression list before assigning:
expr =
Hold[
{
Min[data], Max[data], Covariance[data, data1], Mean[data],
GeometricMean[data], Total[data],
Sum[Log[data[[i]]], {i, 1, Length[data]}],
Sum[(data[[i]])^2, {i, 1, Length[data]}]
}
]
With a new version of exprShowAndEvaluate we can process expr:
ClearAll[exprShowAndEvaluate];
exprShowAndEvaluate[expr_Hold] :=
Module[{tempExpr},
tempExpr = ReleaseHold[Map[HoldForm, expr, {2}]];
Print[#1, "=", ReleaseHold[#1]] & /@ tempExpr
];
The function can now be called with the held list:
exprShowAndEvaluate[expr]
Results as before.
As a sidebar, you have two functions that can be simplified:
Sum[Log[data[[i]]], {i, 1, Length[data]}]
Sum[(data[[i]])^2, {i, 1, Length[data]}]
Since version 6, these can be written more concisely and readably:
Sum[Log[i], {i, data}]
Sum[i^2, {i, data}]
精彩评论