Search code examples
for-loopvectorparipari-gp

Looping over specific values in PARI/GP


I have a large collection of vectors, each of the form [a,b,c,d].

For each vector, I want to return the result [a,b,c,d,a+b^2+c^3+d^4]. What would be the best way of doing this?

For example, say my vectors are V = [ [1,2,3,4], [5,6,7,8], [9, 10, 11, 12] ]. Would the best way to do this be defining a function such as:

test( W ) = for( i=1, #W, print( [ [W[i][1],W[i][2],W[i][3],W[i][4],W[i][1]+W[i][2]^2+W[i][3]^3+W[i][4]^4] ] ) ) ?

(Keeping in mind that in practice I will also have a larger collection of vectors)

This feels like a naive way of doing this, so is there a better way? In particular, is this the quickest way? Is there a better way to store my collection of vectors?


Solution

  • Use matrix to store the vector of vectors. Then just append the new column containing the sum of your exponentials. See the example:

    V = [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]];  /* your vector of vectors */
    
    M = matconcat([V[1]; V[2]; V[3]]);
    M_log = log(M);
    
    matconcat([M, M[,1] + exp(2*M_log[,2]) + exp(3*M_log[,3]) + exp(4*M_log[,4])])
    > [1  2  3  4 288.00]
    > [5  6  7  8 4480.00]
    > [9 10 11 12 22176.00]