Karim Belabas on Sun, 07 Jan 2024 17:22:30 +0100


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

Re: Two questions about vector and matrix manipulation


* Bill Allombert [2024-01-07 14:27]:
[...]
> > 2) Suppose I have two vectors of inconsistent length. I want a third vector
> > representing their sum, as if the shorter vector had been padded with zeros
> > like so:
> >  f(a,b)=my(k=#a-#b);c=vector(abs(k));if(k>0,b=concat([b,c]),a=concat([a,c]));return(a+b)
> > Is there a better/more elegant way to do this?
> 
> Well you can use Vec(...,n) to pad with 0.
> f(a,b)=a=Vec(a,#b);vector(#a,i,a[i]+b[i])
> 
> ? f([1,2],[1,2,3])
> %5 = [2,4,3]

If you want the code to work also when b is the shortest vector, you have to
complicate it a little:
  f(a,b)=
  {
     if (#a < #b, a = Vec(a,#b),
         #a > #b, b = Vec(b,#a));
     vector(#a,i, a[i] + b[i]);
  }

Another possibility is

  f(a,b) =
  {  my (A = #a, B = #b);
     vector(max(A,B), i, if (i > A, b[i],
                             i > B, a[i], a[i] + b[i]));
  }

Probably not more elegant, and certainly slower (evaluating a more
complicated expression is more expensive than adding 0)

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/