1

I have a function to built a polynomial from a given x: [1, x^2,x^3,x^4,...,x^degree]

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.c_[polyome, x**i]

    return polyome

Now, I would like to calculate polynom for a given x, but omiting sume values.

Hence, what this is what I did:

Created X:

x=np.array([[1,2,3],[4,5,6]])])

enter image description here

I masked away the value with I wanted to omit:

masked_x= np.ma.masked_equal(x, 5)
print(masked_x)

enter image description here

But when I do the computation:

print(build_poly(masked_x,2))

enter image description here

The masking has disappeeared. Why ? I want to have the program omit the masked elements

1
  • Immediately after the for statement, add print(i,x**i). Commented Oct 22, 2017 at 16:05

1 Answer 1

1

Apparently when working with masked arrays one must consistently use the numpy.ma versions of the routines. Any departure from this, and numpy 'forgets' that masked elements are present.

def build_poly(x, degree):
    """polynomial basis functions for input data x, for j=0 up to j=degree."""
    D = len(x)
    polyome = np.ones((D, 1))
    for i in range(1, degree+1):
        polyome = np.ma.concatenate([polyome, np.ma.power(x,i)], axis=1)
    return polyome
Sign up to request clarification or add additional context in comments.

6 Comments

Right, the key is to use the 'masked' aware version of concatenate.
Not to mention ma.power.
Though masked_x**2 works just as well for me. Via __pow__ it delegates to np.ma.power.
okay, thanks !! Do you know another way to omit some specific elements of a 2d array when computing ?
@hpaulj: Not something I knew. I was mainly concerned that someone referring to this question wouldn't miss that both places in the code needed attention.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.