a question about the assignment operator '=' for jitter matrices in javascript

adamklec's icon

Hello. I'm writing a javascript patch to manipulate some data stored in a jitter matrix and I am puzzled by something seems like it ought to be simple and straightforward. Can someone please help me with the following piece of code?

//create two matrices
var matrix1= new JitterMatrix(1,'float32',3,3);
var matrix2 = new JitterMatrix(1,'float32',3,3);

matrix1.setcell2d(1,1,5);  //set the (1,1) element of matrix1 equal to 5
post(matrix1.getcell(1,1));  // -->5  so far so good

//Copy the values from matrix1 to matrix2
matrix2 = matrix1;  

//If an element in matrix1 element equals 5,
//the corresponding element in matrix2 should equal 1.
//Otherwise it should equal 0
matrix2.op('==',5);  

post(matrix1.getcell(1,1)); // -->1 ??????????????

It seems that by operating on matrix2 I have changed the value of matrix1. I suspect that after the '=' operator matrix1 and matrix2 are referring to the same data. Is this correct? What is the correct way to perform this type of operation in javascript/jitter?

Thanks,
Adam

adamklec's icon

Ah. If I do the assignment with a jit.expr object the problem goes away.

Peter Castine's icon

You need to spend some quality time with a good JavaScript reference or tutorial. Assignment does not copy values from one matrix to another, it just assigns the reference. After

matrix2 = matrix1;

both variables refer (in C-Speak: point to) the same data.

If you want a deep copy, you need to write your own routine. This is useful with complex data structures, because you may want copies of certain components while using references to others.

And, if jit.expr gets you through the night, then use that.

Jesse's icon

The frommatrix() function in JitterMatrix will do a deep copy of the matrix values. I believe you would call as follows:

matrix2.frommatrix( matrix1 );

or

matrix2.frommatrix( matrix1.name );

adamklec's icon

Thank you. That answers my question.