1
$\begingroup$

I am trying to compute some objects inside while loops within modules, but I keep getting the following error:

Set::write: "Tag Times in <blah> Null is Protected."

I have made this minimal example to illustrate what I want to do - sum each output of a while loop then output the final sum:

f[x_] := Module[{n = 1, m = 1, output = 0, y, z},
  While[m < 5,
    While[n < 5,
       y = x^(m + n) z^m;
       n++;
       ]
      output = y + output;
    m++;
    ]
   output
  ]

f[5]

In my mind this should produce a Polynomial in z. What am I doing wrong?

$\endgroup$
3
  • $\begingroup$ I suspect you get an error due to z not being defined and you don't solve for it in your code. This is why you get an error $\endgroup$ Jan 31 '16 at 13:39
  • 3
    $\begingroup$ You have missing semicolons after While loops. $\endgroup$
    – Kuba
    Jan 31 '16 at 13:53
  • 2
    $\begingroup$ You need ; after your closing braces for the Whiles. Without these your are multiplying output by the While blocks. $\endgroup$
    – JJM
    Jan 31 '16 at 13:53
1
$\begingroup$

As mentioned in the comments you are not suppressing the output of the While statements with a semicolon.

However, you still will not get the result you are expecting because you have scoped z inside of Module and your output will return a variable that is no longer in scope (a Unique variable from the Module).

An example of a Wolfram Language way of coding this is:

f[x_] = Total@Flatten@Table[x^(m + n) z^m, {m, 4}, {n, 4}];

This is a case where using Set (=) instead of SetDelayed (:=) makes the code faster.

Now you will get the results you expect.

f[1]

4 z + 4 z^2 + 4 z^3 + 4 z^4

Hope this helps.


Update OP's loops are to 4 not 5. Have updated for this.

$\endgroup$
4
  • $\begingroup$ I think f[1] should be z + z^2 + z^3 + z^4 $\endgroup$
    – m_goldberg
    Jan 31 '16 at 14:25
  • $\begingroup$ @m_goldberg It is 5 by 5 not 5 by 1. $\endgroup$
    – Edmund
    Jan 31 '16 at 14:45
  • $\begingroup$ The OP's while-loops loop from 1 to 4 in both loops. $\endgroup$
    – m_goldberg
    Feb 1 '16 at 2:37
  • $\begingroup$ @m_goldberg Yes. That is correct. 4 by 4. Not 4 by 1 as you suggested. But not 5 by 5 as I originally read it. I`ll update. $\endgroup$
    – Edmund
    Feb 1 '16 at 2:40
1
$\begingroup$

There are basically two errors in your code: misplaced semicolons and not initializing n at the right point of the code. Also, I think it would good if you allowed the free variable to passed to f, rather than hard wiring it into f.

f[x_?NumericQ, z_Symbol] :=
  Module[{n, m = 1, output = 0, y},
    While[m < 5,
      n = 1;
      While[n < 5, y = x^(m + n) z^m; n++];
      output = y + output;
      m++];
    output]

With this

f[1, x]

x + x^2 + x^3 + x^4

and

f[5, z]

3125 z + 15625 z^2 + 78125 z^3 + 390625 z^4

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.