Bill Allombert on Sun, 07 Jan 2024 14:26:59 +0100


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

Re: Two questions about vector and matrix manipulation


On Sun, Jan 07, 2024 at 05:25:22PM +1100, Joe Slater wrote:
> Thanks for the responses to my previous question. I have a couple of
> queries regarding vectors and matrices.
> 
> 1) Suppose I want a vector representing the pairwise product of two similar
> vectors. Is there a faster/more elegant way to return this product other
> than explicitly multiplying each element? That is, something better than
> this:
> a=[1,2,3];b=[4,5,6];c=vector(#a,i,a[i]*b[i])
> 
> I need the solution to also work if the elements of one vector are also
> vectors:
> a=[[1,2],[3,4]];b=[4,5];c=vector(#a,i,a[i]*b[i])

This is probably the best.

> 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]

Cheers,
Bill.