Group Abstract Group Abstract

Message Boards Message Boards

Error: Set::setraw: Cannot assign to raw object 9

GROUPS:
 Clear["Global`*"];
 Distribuciondefinida[\[Mu]_, \[Sigma]_, x1_, s_,
   k_] :=
  (xy = Table[x1, {1}]; n = Length[xy];
   While[n < k, n++;
    U1 = RandomReal[];
    x1 = Last[xy];
    If[U1 < 0.5, y = x1 + s, y = x1 - s];
    r = (PDF[NormalDistribution[\[Mu], \[Sigma]], y]/
      PDF[NormalDistribution[\[Mu], \[Sigma]], x1]);
   U2 = RandomReal[];
   If[U2 < r, y = y, y = x1]; xy = Append[xy, y]];
  xy)
I have trying to define de function Distribuciondefinida[\_, \_, x1_, s_,
k_] as above, but when I type "Distribuciondefinida[100, 2, 99, 0.1, 100]" the message " Set::setraw: Cannot assign to raw object 9" appears.  I do not understand how to solve it.  Thank you very much.
POSTED BY: fgarcia
Answer
8 months ago
There are few problems with the code:
  1. do not use Uppercase first letter for variable names since these are meant for use by Mathematica own symbols and variables.
  2. do not use global variables. Your function had many of these. Make a module, and make module level variables for use.
  3. do not assign value fo input arguments as these are passed as read only (by value) as the default passing mechanism. (this is the reason for the error message)
 Clear["Global`*"];
 distribuciondefinida[mu_, sigma_, xx1_, s_, k_] :=  Module[{u1, u2, xy, n, y, x1 = xx1, r},
   xy = {x1}; (*Table[x1,{1}];*)
   n = 1; (*Length[xy];*)
  
   While[n < k,
    n++;
    u1 = RandomReal[];
    x1 = Last[xy];
   
   If[u1 < 0.5, y = x1 + s, y = x1 - s];
   
   r = (PDF[NormalDistribution[mu, sigma], y]/PDF[NormalDistribution[mu, sigma], x1]);
   u2 = RandomReal[];
   If[u2 < r, y = y, y = x1];
   xy = Append[xy, y]
   ];
 
  xy
  ]
now
distribuciondefinida[100, 2, 99, 0.1, 100]
does not generate an error.
POSTED BY: Nasser
Answer
8 months ago
Hi Nasser.  Thank you verymuch!  I was whole morning trying to fix this.
POSTED BY: fgarcia
Answer
8 months ago