字符串表单列表功能

时间:2012-01-11 18:11:50

标签: wolfram-mathematica

我正在使用Mathematica 5.2版。我需要将它拆分为函数,并生成结果..     我创造了这个怪物:

mx = {};
arg = {};
fun = {}; 
x =. 
y =.

这里是列表和参数

switchfunction2[y_] := Switch[y,
  1, AppendTo[fun, Cos[Random[Integer, {1, 10}]]],
  2, AppendTo[fun, Sin[Random[Integer, {1, 10}]]],
  3, AppendTo[fun, Tan[Random[Integer, {1, 10}]]],
  4, AppendTo[fun, Csc[Random[Integer, {1, 10}]]],
  5, AppendTo[fun, Sec[Random[Integer, {1, 10}]]],
  6, AppendTo[fun, Cot[Random[Integer, {1, 10}]]]
]

和随机函数

Do[AppendTo[mx, Random[Integer, {1, 10}]], {i, 2}] 

mx[[1]] " has been chosed"
mx[[2]] "argumments "
Do[AppendTo[arg, Random[Integer, {1, 5}]], {i, mx[[2]]}] 
arg
Do[switchfunction2 /@ {arg[[i]]}, {i, mx[[2]]}]
fun

我想获得f[z_]:=fun[[1]]+fun[[2]]...

1 个答案:

答案 0 :(得分:4)

在这种情况下,我会做类似

的事情
mx = RandomInteger[{1, 10}, 2];
arg = RandomInteger[{1, 5}, mx[[2]]];

switch[y_] := Module[{f},
  f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
  f[RandomInteger[{1, 10}]]]

fun = switch /@ arg;

Total[fun]

或者不使用开关功能:

mx = RandomInteger[{1, 10}, 2]
flist = RandomChoice[{Cos, Sin, Tan, Csc, Sec, Cot}, mx[[2]]];

fun = #[RandomInteger[{1, 10}]] & /@ flist;
Total[fun]

修改

这是一个适用于Mathematica 5.2的版本。

mx = Table[Random[Integer, {1, 10}], {2}];
arg = Table[Random[Integer, {1, 5}], {mx[[2]]}];

switch[y_] := Module[{f}, 
  f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
  f[Random[Integer, {1, 10}]]]

fun = switch /@ arg;

Total[fun]

要创建一个函数,你可以将所有内容包装在Module中,例如

f := Module[{mx, arg, switch},
  mx = Random[Integer, {1, 10}];
  arg = Table[Random[Integer, {1, 5}], {mx}];
  switch[y_] := Module[{f}, 
    f = Switch[y, 1, Cos, 2, Sin, 3, Tan, 4, Csc, 5, Sec, 6, Cot];
    f[Random[Integer, {1, 10}]]];
  Total[switch /@ arg]]