I'm attempting to write a little function where it takes 2 vectors, changes the sign on the first entry of the first vector and then perform the dot product on them. However, when I do this, the global value of the changed vector in the function is changed outside the function.
I've attempted to use the block
function to protect the global values of the vectors, but this doesn't seem to change anything.
a: matrix([3],[4],[5]);
b: matrix([4],[5],[6]);
f(x,y):=block([x:x,y:y],x[1]:-x[1],x.y);
f(a,b);
I expect the answer to be 38, which it is on the first time I run f(a,b);
but when I do it a second time, I get 62 because a
has changed globally.
You pass a matrix to the function, and this matrix is not copied, it's a reference to the same matrix. As Maxima documentation says,
Matrices are handled with speed and memory-efficiency in mind. This means that assigning a matrix to a variable will create a reference to, not a copy of the matrix. If the matrix is modified all references to the matrix point to the modified object (See copymatrix for a way of avoiding this)
So you need to copy a matrix to handle it independently:
f(x,y):=block([x:x, y:y, m:m, n:n],
m:copymatrix(x),
n:copymatrix(y),
m[1]:-m[1],
m.n);