mathjs

How to declare a function with more than one statement in Mathjs?


I'm trying to collect several columns of mathjs statements and execute them each against an incrementing counter x (1, 2, 3...). After each column has been executed by mathjs, extract the value of y.

For example:

System input:
x=0    x=1    x=2    x=3
------------------------
User input:
a=1    a=4    a=x        
y=a    y=a-4  y=a-1  y=x
------------------------
Output: 
1      0      1      3

There is an additional complication to my problem: each column is 1 second, and we desire to create the waveform of an audio file. That means, between each column, interpolate the values of x 44099 times (for sample rate 44100).

It's easy enough to create a range for x, x*44100:1:(x+1)*44100. But the tricky part is how to evaluate each of the intervening columns to efficiently extract y. You can see how this might be necessary for a sine wave which fluctuates many times a second, with something like y=sin(x). We don't just want the audio file to have a point at x=0 seconds and another point at x=1 seconds with nothing in between.

To do this efficiently, my first idea was to declare the entire column as an f(x), eval it with mathjs, and extract y. But it seems like mathjs functions can only consist of a single statement.

For example, this fails:

f(x) = d = 1; d
f(3) // expect 1; actual: error

I understand this is the classic "XY problem" (ha!), but I will certainly accept an answer that solves my X problem instead.


Solution

  • There is no current syntax to do that. A workaround is that elements of an array can include expressions with assignments.

    f( ) = [d = 1, d][end] # evaluate all expressions in the array and return only the value of the last expression.
    f( )                   # 1
    

    You have to be very careful with your naming convention as the expressions will assign values in the scope (there are not function scopes)