HP Forums
How to obtain element-wise squaring of vector/matrix? - Printable Version

+- HP Forums (https://www.hpmuseum.org/forum)
+-- Forum: HP Calculators (and very old HP Computers) (/forum-3.html)
+--- Forum: HP Prime (/forum-5.html)
+--- Thread: How to obtain element-wise squaring of vector/matrix? (/thread-14057.html)



How to obtain element-wise squaring of vector/matrix? - mbeddo - 11-26-2019 07:40 PM

I'm implementing a non-linear fitting routine and [/code]I need to square the elements of a vector from within a program. From the CAS screen I can easily square the elements of a vector [1, 2, 3, 4]:
[attachment=7858]

The simple program below has a syntax error:

Code:

EXPORT DEMO()
BEGIN
  LOCAL myvec;

  myvec := [1, 2, 3, 4];
  apply(x→x^2, myvec);
END;

I don't know what I'm doing wrong.

I looked for a function that would square element-wise, and "apply" seemed to fit the bill. I'm trying to avoid a FOR loop.

I think it would be easier if I just squared a list of numbers, then converted the answer to a vector?


RE: How to obtain element-wise squaring of vector/matrix? - swagner53 - 11-26-2019 08:47 PM

Hi,

apply is a CAS command that does not work under Home. Try converting to a CAS program by sandwiching your code between #cas and #end. Hopefully, that will work.

Take care & good luck, Steve


RE: How to obtain element-wise squaring of vector/matrix? - goetz - 11-26-2019 11:18 PM

Alternatively you could also use the "point" operator .^ for element wise power operator on a vector or matrix , e.g.:

Code:
[1, 2, 3, 4].^2

resulting in: [1, 4, 9, 16]


RE: How to obtain element-wise squaring of vector/matrix? - mbeddo - 11-27-2019 07:16 AM

(11-26-2019 08:47 PM)swagner53 Wrote:  Hi,

apply is a CAS command that does not work under Home. Try converting to a CAS program by sandwiching your code between #cas and #end. Hopefully, that will work.

Take care & good luck, Steve

I found this works:
Code:

#cas
DEMO2():=
BEGIN
  apply(x→x^2, [1, 2, 3, 4]);
END;
#end

Thanks!


RE: How to obtain element-wise squaring of vector/matrix? - mbeddo - 11-27-2019 07:20 AM

(11-26-2019 11:18 PM)goetz Wrote:  Alternatively you could also use the "point" operator .^ for element wise power operator on a vector or matrix , e.g.:

Code:
[1, 2, 3, 4].^2

resulting in: [1, 4, 9, 16]

Fantastic!

It seems I still have a ways to go digesting the reference manual - these point operators didn't register while searching for element-wise operators. Guess I have a ways to go to learn how to search the documents.