Karim Belabas on Thu, 21 Mar 2024 18:13:47 +0100


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Error in pari/gp code


* Swati, NoFirstName [2024-03-21 17:10]:
> Hi,
> I am trying to write a code to output the position of the last non-zero entry of this matrix but the code is giving a syntax error. I am not sure what went wrong. Could someone help in this regard?
> 
> Thanks,
> Swati
> 
> C = [[1, 2, 3, 4], [7, 9, 10], [25, 31, 0], [0, 0, 0]];
> A = matconcat([C[1]; C[2]; C[3]; C[4]]);
> 
> R = 0;
> C = 0;
> S= 0;
> 
> for(i = matsize(A)[1], i >= 1 &&  S == 0, i--,
>     for(j = matsize(A)[2], j >= 1 &&  S== 0, j--,
>         if(A[i, j] != 0,
>             R = i;
>             C = j;
>            S = 1;
>             break;
>   )))
> 
> if(S == 1,
>     print("Position of the last non-zero entry:" [R, C]),
>     print("Matrix A contains only zeros.")
> );
> 

Here's a corrected version

  {
    my (R = 0, C = 0);
    forstep(i = matsize(A)[1], 1, -1,
      forstep(j = matsize(A)[2], 1, -1,
        if(A[i, j] != 0, R = i; C = j; break(2))));
    if (R,
      print("Position of the last non-zero entry: ", [R, C])
    ,
      print("Matrix A contains only zeros."));
  }

  Position of the last non-zero entry: [3, 2]

Cheers,

    K.B.
-- 
Pr. Karim Belabas, U. Bordeaux, Vice-président en charge du Numérique
Institut de Mathématiques de Bordeaux UMR 5251 - (+33) 05 40 00 29 77
http://www.math.u-bordeaux.fr/~kbelabas/