Home > Back-end >  Putting 2×2 matrices in ndarray without using "for"
Putting 2×2 matrices in ndarray without using "for"

Time:10-28

Numpy

First, I define "x" and function "example" below:

import numpy as np
x=np.arange(1,4,1)
def example(d):
    return 2*d

In this simple case, if I put "x" into "example",

y=example(x)

I get "y", which has a same length as x and I can calculate quickly.

However, if I define example2 as below,

def example2(d):
    matrix=np.array([[d,0],[0,d])
    return matrix

and input "x" into example2,

y2=example2(x)

What I get is

[[array([1, 2, 3]) 0]
 [0 array([1, 2, 3])]]
<ipython-input-9-21f94eb7b4f4>:2: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  matrix=np.array([[d,0],[0,d]])

There is a warning as well.

I really want to create a ndarray(or list) which contain a matrix in each term without using "for". I can do this if I use "append", but it takes much longer to finish calculations.

A1=np.array([[1,0],[0,1]])
A2=np.array([[2,0],[0,2]])
A3=np.array([[3,0],[0,3]])
y3=np.array([A1,A2,A3])

If I name each matrix A1,A2,A3, which are created in example2, what I want to do is to create y3 by just inputting "x" into a function I created.

Are there any solutions?

CodePudding user response:

not following but:


import numpy as np


x=np.arange(1,4,1)
def example(d):
    return 2*d


y=example(x)

print(y)

def example2(d):
    matrix=np.array([[d,0],[0,d]], dtype= object)
    return matrix



y2=example2(x)

print('\n___________________________')
print(y2)

gives:

[2 4 6]

___________________________
[[array([1, 2, 3]) 0]
 [0 array([1, 2, 3])]]

so no error, not sure it is was you were looking for, just post your desidered output to help the others to help you

CodePudding user response:

You could initial an array of the desired shape, and assign selected values:

In [93]: arr = np.zeros((3,2,2),int)
    ...: arr[:,0,0] = [1,2,3]
    ...: arr[:,1,1] = [4,5,6]
    ...: 
    ...: 
In [94]: arr
Out[94]: 
array([[[1, 0],
        [0, 4]],

       [[2, 0],
        [0, 5]],

       [[3, 0],
        [0, 6]]])

The same thing, but with one advanced-indexing assignment:

In [97]: arr = np.zeros((3,2,2),int)
    ...: arr[:,[0,1],[0,1]] = np.array([[1,2,3],[4,5,6]]).T 
In [98]: arr
Out[98]: 
array([[[1, 0],
        [0, 4]],

       [[2, 0],
        [0, 5]],

       [[3, 0],
        [0, 6]]])

This required several attempts, since I was getting broadcasting errors. Getting dimensions right when making assignments like this is tricky.

  • Related