Bill Allombert on Mon, 18 Nov 2024 19:22:02 +0100


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

Re: Is there a function for sum of square matrix antidiagonal like "trace()" for main diagonal?


On Mon, Nov 18, 2024 at 06:29:55PM +0100, hermann@stamm-wilbrandt.de wrote:
> On 2024-11-18 16:59, Loïc Grenié wrote:
> > > > 
> > > trace(op(~M)) is slower than atr2, but I finally got it:
> > > 
> > > op(~M)=Mat([M[-i,]~|i<-[-#M..-1]]);
> > 
> > op(M)=Mat(Vecrev(M));
> > 
> >   but I expect it to be slower than the sum (too many copies).
> > 
> Thank you, I have used Vecrev() before, but did not think about it.
> And yes and no regarding slower:
> While "trace(op(~M))" is slower, moving "trace()" into "op()"
> makes it slightly faster than atr2 from Bill:
> 
> ? atr2
> (~M)->sum(i=1,#M,M[i,#M+1-i])
> ? for(i=1,100000,atr2(~M))
> cpu time = 615 ms, real time = 614 ms.
> ? op(~M)=trace(Mat(Vecrev(M)));
> ? for(i=1,100000,op(~M))
> cpu time = 589 ms, real time = 591 ms.

I would be very happy if that were true, but

M=matrix(100,100,i,j,random(1000));
atr2(~M)=sum(i=1,#M,M[i,#M+1-i]);
op(~M)=trace(Mat(Vecrev(M)));
for(i=1,100000,atr2(~M))
  ***   last result computed in 1,201 ms.
for(i=1,100000,op(~M))
  ***   last result computed in 11,051 ms.

I assume your matrix is very small ?

Cheers,
Bill.