In the past I have pretty much stuck to expression building when using Mathematica, but recently I have been writing a procedure to populate an array, which I guess are called "lists" in Mathematica. The list is generated from two random sequences, one of which is weighted more heavily than the other. Because of an "offset" parameter which itself is randomized, I could only think of a "Do" method of making my output as follows:
min = 0;
max = 10000;
k := 0.5;
RandomValue := RandomReal[{min, max + max *k}];
randomA = RandomReal[{min, max}, 1000];
randomB = RandomReal[{min, max}, 1000];
Clear[effect];
effect = Range[1000];
Module[{offset},
Do[
offset = RandomInteger[{1, 10}];
If[ xEffect - offset < 1 ,
effect[[ xEffect ]] = RandomValue,
effect[[ xEffect ]] = randomA[[ xEffect - offset ]] + k * randomB [[ xEffect - offset ]] ];
, { xEffect, 1, 1000 }]
];
Take[effect, 20]
(* Out: {9118.77, 12599.2, 3892.83, 5083.62, 12517.1, 9102.53, \
5083.62, 5083.62, 5083.62, 9801.6, 8169.35, 9801.6, 3809.98, 8169.35, \
9801.6, 8670.78, 9443.65, 9026.42, 3013.94, 3013.94} *)
The output looks plausible (except some bug is causing sequential values in the output array to be duplicated sometimes) so my code seems to be kind of correct. My questions are: (1) Is there a better way to write this as functional, rather than procedural code? (2) I clear and initialize my "effect" global before running the module to populate it, do I need to do this? Another bizarre issue I don't understand, is that sometimes when I run it, I get output like this:
Take[effect, 20]
{9102.53, 1.5 List, 13497.6, 7457.65, 12517.1, 8869.53, 5603.8, 7457.65, \
5603.8, 8869.53, 11289.6, 3809.98, 12517.1, 7427.27, 3809.98, \
9211.48, 8670.78, 3013.94, 7229.46, 3809.98}
Why would one of the elements be "1.5 List" ?
List
, Mr. Montoya, is thatxEffect
can be0
, and the0
th element of an expression is itsHead
:{}[[0]] === List
. $\endgroup$xEffect - offset
can be zero $\endgroup$