Applying A Mask To Matrices Gives Different Objects In Numpy
I've mostly worked with MATLAB, and I am converting some of my code that I have written into Python. I am running into an issue where I have a boolean mask that I am calling Omega, and when I apply the mask to different m by n matrices that I call X and M I get different objects. Here is my code
import numpy as np from numpy import linalg as LA m = 4 n = 3 r = 2 A = np.matrix('1 0; 0 1; 1 1;1 2') B = np.matrix('1 1 2; 0 1 1') M = A @ B Omega = np.matrix('1 1 1;1 1 1;1 1 0;1 0 0',dtype=bool) #mask X = np.copy(M) X[~Omega] = 0 U, S, Vh = LA.svd(X) #singular value decompostion of X Sigma = np.zeros((m,n)) np.fill_diagonal(Sigma,S) X = U[:,0:r] @ Sigma[0:r,0:r] @ Vh[0:r,:] print(X[Omega]) print(M[Omega]) X[Omega] = M[Omega]
I get the error "NumPy boolean array indexing assignment requires a 0 or 1-dimensional input, input has 2 dimensions" on the last line. However, the issue seems to be that X[Omega] and M[Omega] are different objects, in the sense that there are single brackets around X[Omega] and double brackets around M[Omega]. In particular, the print commands print out
[0.78935751 1.12034437 2.01560085 0.4845614 0.72316014 0.96411184 1.10709648 1.93881358 0.24918864] [[1 1 2 0 1 1 1 2 1]]
How can I fix this?
M is a
np.matrix, which are always 2-D (so it has two dimensions). As the error message indicates, you can only use a 0- or 1-D array when assigning to an array masked with a boolean mask (which is what you're doing).
M to an array first (which, as @hpaulj pointed out, is better than using
X[Omega] = M[Omega].A1
>>> X array([[ 1. , 1. , 2. ], [ 0. , 1. , 1. ], [ 1. , 2. , -0.00793191], [ 1. , 0.42895392, 0.05560748]])
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module