wolfram-mathematica - 在 Mathematica 中对数字列表进行平方

标签 wolfram-mathematica

因此,对于我的离散数学建模课上的家庭作业问题,我们被要求在 Mathematica 中创建一个函数,该函数输入一个列表并对列表中的每个元素进行平方。这是一项简单的任务,我已经完成了以下操作:

sqList[list_] = (list)^2;

但我想用“for 循环”来做到这一点。这是我的代码:

sqList2[list2_] :=
  (
    For[j = 1, j <= Length[list2], j++,
    (
     list2[j]^2;
     )];
   list2
  );

我更习惯 Matlab,并且正在努力提升学习曲线。这段代码对我来说很有意义,并且非常感谢我应该采取的任何指示。我尝试过调试这段代码,但就像我说的,我不习惯这个程序,也不习惯它的堆栈跟踪。我找不到任何问题,但它输出了我输入的确切列表。

最佳答案

使用示例列表

list = {1, 2, 3};

sqList[list_] := list^2

sqList[list]

{1, 4, 9}

这之所以有效,是因为 Power (^) 是可列出的:

Attributes[Power]

{Listable, NumericFunction, OneIdentity, Protected}

逐个元素处理列表

sqList2[list2_] := Module[{squaredlist = {}, j},
  For[j = 1, j <= Length[list2], j++,
   AppendTo[squaredlist, list2[[j]]^2]];
  squaredlist]

sqList2[list]

{1, 4, 9}

或者可以使用 map

sqList3[list3_List] := Map[#^2 &, list3]

sqList3[list]

{1, 4, 9}

注意

这种形式的函数与您尝试过的函数接近,但不会起作用,因为 list2 是一个输入变量并且无法修改。

sqList2[list2_] := (
  For[j = 1, j <= Length[list2], j++,
   list2[[j]] = list2[[j]]^2];
  list2)

使其工作的最小修改是:-

sqList2[list2input_] := (
  list2 = list2input;
  For[j = 1, j <= Length[list2], j++,
   list2[[j]] = list2[[j]]^2];
  list2)

此外,For循环不输出运行结果;这就是为什么需要在循环内收集输出。

关于wolfram-mathematica - 在 Mathematica 中对数字列表进行平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272686/

相关文章:

plot - Mathematica 分段函数错误的绘图渲染

wolfram-mathematica - 为什么使用牛顿法的 FindMaximum 会提示找不到足够的函数减少?

wolfram-mathematica - 在需要时在行之间的网格内添加分隔线的任何技巧

wolfram-mathematica - 将东西放入 HoldPattern

wolfram-mathematica - 有没有办法从 Mathematica 的列表中删除元素

statistics - Mathematica、PDF 曲线和阴影

math - 计算点到线段和线段到线段的平均距离

r - 制作 3d 表面

arrays - 有没有什么有效的简单方法可以用 Mathematica 比较两个长度相同的列表?

exception - 在mathematica中找不到文件时抛出异常