通过循环创建多个变量/列表/函数(Maxima)

时间:2016-06-08 01:24:10

标签: maxima

下面我列出了一些通过千里马的for循环创建变量/列表/函数的方法 但是,通过for循环,如何做:

f1(x) := x^1$
f2(x) := x^2$
f3(x) := x^3$

示例代码:

for i : 1 thru 10 do
(x : concat ('a, i), x :: i)$
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];

for i : 1 thru 3 do
(x : concat ('L, i), x :: [(3*i)-2,(3*i)-1,3*i])$
[L1, L2, L3];

/* good, but not quite what I want to do */
for i : 1 thru 3 do
f[i](x) := x^i$
[f[1](2), f[2](2), f[3](2)];

/* is there a way, via a for loop, to create */
f1(x) := x^1$
f2(x) := x^2$
f3(x) := x^3$
[f1(2), f2(2), f3(2)];

编辑:进一步的代码:

/* is there a way, via a for loop, to create */
f(x) := x^1$
g(x) := x^2$
h(x) := x^3$
[f(2), g(2), h(2)];

for tmp1 : 1 thru 10 do
(tmp2 : parse_string(ascii(96+tmp1)), tmp2 :: tmp1)$
[a, b, c, d, e, f, g, h, i, j];

for tmp1 : 1 thru 10 do
(tmp2 : concat(parse_string(ascii(96+tmp1)), tmp1), tmp2 :: tmp1)$
[a1, b2, c3, d4, e5, f6, g7, h8, i9, j10];

编辑2:解决了原始问题(欢迎任何代码改进/简化):

for i : 1 thru 3 do
eval_string(concat("f", i, "(x) := x^", i))$
[f1(2), f2(2), f3(2)];

for i : 1 thru 3 do
eval_string(concat(ascii(96+5+i), "(x) := x^", i))$
[f(2), g(2), h(2)];

sum:0$
for i : 1 thru 3 do
sum:sum + eval_string(concat("f", i, "(2)"))$
sum;

sum:0$
for i : 1 thru 3 do
sum:sum + eval_string(concat(ascii(96+5+i), "(2)"))$
sum;

2 个答案:

答案 0 :(得分:1)

你的目标是什么?通常使用下标符号,例如a[1]而不是a1是首选。定义下标函数时,只需定义一次,而不是定义下标的每个值。例如。

(%i1) f[i](x) := x^i $
(%i2) [f[1], f[2], f[3]];
                                            2                3
(%o2)         [lambda([x], x), lambda([x], x ), lambda([x], x )]
(%i3) [f[1](u), f[2](v), f[3](w)];
                                       2   3
(%o3)                             [u, v , w ]

如果这对你不起作用,也许你可以解释一下你想要实现的目标。

答案 1 :(得分:0)

我在这里收集了各种方法,通过Maxima中的循环创建多个变量/列表/函数, 作为问题的答案,'[f1(2),f2(2),f3(2)]'明确回答了原来的问题:

for i : 1 thru 10 do
(x : concat ('a, i), x :: i)$
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];

for i : 1 thru 3 do
(x : concat ('L, i), x :: [(3*i)-2,(3*i)-1,3*i])$
[L1, L2, L3];

for tmp1 : 1 thru 10 do
(tmp2 : parse_string(ascii(96+tmp1)), tmp2 :: tmp1)$
[a, b, c, d, e, f, g, h, i, j];

for tmp1 : 1 thru 10 do
(tmp2 : concat(parse_string(ascii(96+tmp1)), tmp1), tmp2 :: tmp1)$
[a1, b2, c3, d4, e5, f6, g7, h8, i9, j10];

for i : 1 thru 3 do
eval_string(concat("f", i, "(x) := x^", i))$
[f1(2), f2(2), f3(2)];

for i : 1 thru 3 do
eval_string(concat(ascii(96+5+i), "(x) := x^", i))$
[f(2), g(2), h(2)];

f[i](x) := x^i$
[f[1], f[2], f[3]];
[f[1](2), f[2](2), f[3](2)];
[f[1](u), f[2](v), f[3](w)];
相关问题