1

Basically I am searching for a way to add the letter u to an existing list of variables {a,b,c,d} to obtain the variable list {ua,ub,uc,ud}. I am trying to make an function for an automatic calculation of the propagation of uncertainty.

U[term_Expression, varlist_Expression] := Sqrt[
Sum[i,{i,
Function[var,
  Power[D[term, var], 2]*u] /@ varlist
}]]

The Input U[a*b, {a, b}] gives me Sqrt[a^2*u + b^2*u] but I want it to be Sqrt[a^2*ua + b^2*ub]. Probably this is a very easy task but I am struggling for hours with this small problem. Maybe you know a solution? Thanks!

UPDATE

Made it with

U[term_, varlist_] := Sqrt[Sum[i, {i,
 Power[
  Function[var,
     D[term, var]
     ] /@ varlist*
   ToExpression[StringInsert[#, "u", 1] & /@ ToString /@ varlist]
  , 2]
 }]]

Thank you!

Michael
  • 11
  • 2
  • To make a string out of a symbol sym, use ToString[sym]; to join two strings together use StringJoin[str1,str2]; to make a symbol out of the joined string use ToExpression[str]. Something like ToExpression[StringJoin[ToString[u],ToString[a]]] should create the symbol you want. Now you are left with a pattern matching problem. How much should this task be automated? – Peltio Nov 14 '13 at 12:58
  • StringInsert[#, "u", 1] & /@ ToString /@ {a, b, c, d} produces {"ua", "ub", "uc", "ud"}. – Artes Nov 14 '13 at 12:58
  • Shouldn't U[a*b, {a, b}] be Sqrt[b^2*ua + a^2*ub] -- i.e., a and b reversed because D[a*b, a] = b? – Michael E2 Nov 14 '13 at 14:11
  • Ah, of course you're right. Fixed that – Michael Nov 14 '13 at 15:00
  • Why so you write U[term_Expression, varlist_Expression]? That argument pattern won't accept any normal arguments -- in particular it won't accept U[a*b, {a, b}]. – m_goldberg Nov 14 '13 at 15:06
  • You should take a look at Oleksandr's excellent [CovariancePropagation` package](http://mathematica.stackexchange.com/a/16803/862) – Simon Woods Nov 14 '13 at 20:03

2 Answers2

2

Another option. Use ToExpression to make it a symbol from String

ClearAll[a, b, c, d, u]
lst = {a, b, c, d};
r = Cases[lst, x_ :> ToExpression[ "u" <> ToString[x]]]

FullForm[r]

Mathematica graphics

Nasser
  • 143,286
  • 11
  • 154
  • 359
2

I might do it this way and make the mark of uncertainty a special head u, so that u[a] represents the uncertainty of a, and so forth.

ClearAll[U, u];
SetAttributes[u, HoldAll];
SetAttributes[U, HoldRest];
U[term_, varlist_] := Block[varlist,
  Sqrt[#.#] &[D[term, {varlist}] (u /@ varlist)]
  ]

The symbol u can be substituted with a function or even defined to give the variable ua, ub etc.:

ClearAll[U, u];
SetAttributes[u, HoldAll];
SetAttributes[U, HoldAll];
u[var_] := Symbol["u" <> SymbolName[Unevaluated[var]]];
U[term_, varlist_] := Block[varlist,
  Sqrt[#.#] &[D[term, {varlist}] (u /@ varlist)]
  ]
Michael E2
  • 235,386
  • 17
  • 334
  • 747