Dynamic Variable creation

Jonatan Ewald's icon

Hi!
I want to create dynamic variables within codebox in GEN.
I would like to create a variable such as "var_i" and then in a for loop generate:
var_1
var_2
var_3 etc.
I would then like to dynamically use the History function so I can recall "History var_i" in another for loop.
I want to generate values in a loop and then use the same values for each coming sample in a similar loop.
Is this possible?
What is the code syntax?

Graham Wakefield's icon

It sounds like you want an array. This can be achieved using Data, with peek() and poke() being the methods to read and write respectively. E.g. the following code creates 10 random values, then computes their average:

// allocate space for 10 values:
Data arr(10);

// set to random values:
for (i=0; i
    poke(arr, noise(), i);
}

// add them up
sum = 0;
for (i=0; i
    sum += peek(arr, i);
}

// take the average:
avg = sum / dim(arr);
out1 = avg;

For a real-world usage, see gen~.chopper_repeat.maxpat in the examples folder.

Jonatan Ewald's icon

Thanks!
I solved it now, but using the buffer object and referencing a buffer outside of the GEN object.

If I use the data method can I then use:
History (arr)

or what would be the syntax?
Or is the Data object "arr()" then set and still in the memory for the next samples until I write to it again or how does it work?
I have only found very basic help for the codebox object, is there a complete reference with the syntax and functions used?

Graham Wakefield's icon

"Data arr(10)" in codebox is equivalent to [data arr 10] in the genpatcher. It creates a persistent storage of 10 numbers (64-bit floats), which will always be available. There is no need to refer to a history in this case (and no, "History (arr)" is not valid).

Jonatan Ewald's icon

Thanks a lot Graham!
I have seen many of these but the operator links were new to me and a great help!
I am new to coding except some minor Matlab and basic Excel VBA stuff so this is a great help!
I guess I will have to take a bit more time going through the tutorials instead of jumping right in at the deep end...
But I do feel coding is many times much easier than patching.
Doing stuff similar to "for loops" and such gets very complex very fast when patching.

Is it possible to do more with code also for regular MAX objects?
Code that trigger on bangs and number input change instead of executing on each sample and only using signals like the GEN object?
Or is it possible to work non-sample based in the GEN object?
I have not grasped it completely, but as I understand it the GEN object runs all code for each sample?

Thanks again for the useful info!