Numpy recarray.conjugate () function | python

conjugate | NumPy | Python Methods and Functions

numpy.recarray.conjugate() returns an array by concatenating a complex number in an array.

Syntax: numpy.recarray.conjugate(out=None)

Parameters:

out: [ndarray, optional] A location into which the result is stored.
 - & gt; If provided, it must have a shape that the inputs broadcast to.
 - & gt; If not provided or None, a freshly-allocated array is returned.

Return: Output array with same dimensions as Input array, placed with result.

Code # 1:

# Python program explaining
# numpy.recarray.conjugate () method

 
# import numy as geek

import numpy as geek

 
# create input array

in_arr = geek.array ([[( 4.0 + 1j , 1 + 3j ), ( 5.0 , 5 - 1j ),

( 8.0 - 6j , 9 )], [( 9.0 , 1 ), 

( 7.0 + 1j , 3 - 1j ), ( - 2.0 + 6j , - 7 + 3j )]],

dtype = [( `a` , complex ), ( `b` , complex )])

 

print ( "Input array:" , in_arr)

 
# convert it to an array of posts using arr.view (np. recarray)

rec_arr = in_arr.view (geek.recarray)

 
# 1st array of posts

print ( "1st Record array of complex:" , rec_arr.a)

# applying recarray.conjugate methods to the first array of posts

out_arr = (rec_arr.a) .conjugate ()

print ( "Output 1st conjugated array : " , out_arr) 

  
# 2nd array of records

rec_arr = rec_arr.b

print ( "2nd Record array of complex:" , rec_arr)

  
# applying recarray.conjugate methods to the second array of records

out_arr = rec_arr.conjugate ()

print ( "Output 2nd conjugated array:" , out_arr) 

Output:

 Input array: [[(4. + 1.j, 1. + 3.j) (5. + 0.j, 5.-1.j) (8.-6.j, 9. + 0.j)] [(9. + 0.j, 1. + 0.j) (7. + 1.j, 3.-1.j) (-2. + 6.j, -7. + 3.j)]] 1st Record array of complex: [[4. + 1 .j 5. + 0.j 8.-6.j] [9. + 0.j 7. + 1.j -2. + 6.j]] Output 1st conjugated array: [[4.-1.j 5.-0.j 8. + 6.j] [9.-0.j 7.-1.j -2.-6.j]] 2nd Recor d array of complex: [[1. + 3.j 5.-1.j 9. + 0.j] [1. + 0.j 3.-1.j -7. + 3.j]] Output 2nd conjugated array: [[1.-3.j 5. + 1.j 9.-0.j] [1.-0.j 3. + 1.j -7.-3.j]] 




Numpy recarray.conjugate () function | python: StackOverflow Questions

Answer #1

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product.

import numpy as np

a = np.mat("4 3; 2 1")
b = np.mat("1 2; 3 4")
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print([email protected])
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.

In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise (except for the new @ operator). Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot (or @ in Python >= 3.5, as shown above):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise.

There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).

The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.

Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don"t expect.

In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.

If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.

PS. Of course, you really don"t have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).


There is a synopsis of the differences between NumPy arrays vs NumPy matrixes here.

Answer #2

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays.

Note that while you can use numpy.matrix (as of early 2021) where * will be treated like standard matrix multiplication, numpy.matrix is deprecated and may be removed in future releases.. See the note in its documentation (reproduced below):

It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

Thanks @HopeKing.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you"d expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn"t fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum("ji,i->j", a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy"s implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don"t use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

Answer #3

Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in attributes.

For example you have an object person, that has several attributes: name, gender, etc.

You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.

But what if you don"t know the attribute"s name at the time you write the program? For example you have attribute"s name stored in a variable called attr_name.

if

attr_name = "gender"

then, instead of writing

gender = person.gender

you can write

gender = getattr(person, attr_name)

Some practice:

Python 3.4.0 (default, Apr 11 2014, 13:05:11)

>>> class Person():
...     name = "Victor"
...     def say(self, what):
...         print(self.name, what)
... 
>>> getattr(Person, "name")
"Victor"
>>> attr_name = "name"
>>> person = Person()
>>> getattr(person, attr_name)
"Victor"
>>> getattr(person, "say")("Hello")
Victor Hello

getattr will raise AttributeError if attribute with the given name does not exist in the object:

>>> getattr(person, "age")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: "Person" object has no attribute "age"

But you can pass a default value as the third argument, which will be returned if such attribute does not exist:

>>> getattr(person, "age", 0)
0

You can use getattr along with dir to iterate over all attribute names and get their values:

>>> dir(1000)
["__abs__", "__add__", ..., "__trunc__", "__xor__", "bit_length", "conjugate", "denominator", "from_bytes", "imag", "numerator", "real", "to_bytes"]

>>> obj = 1000
>>> for attr_name in dir(obj):
...     attr_value = getattr(obj, attr_name)
...     print(attr_name, attr_value, callable(attr_value))
... 
__abs__ <method-wrapper "__abs__" of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...

>>> getattr(1000, "bit_length")()
10

A practical use for this would be to find all methods whose names start with test and call them.

Similar to getattr there is setattr which allows you to set an attribute of an object having its name:

>>> setattr(person, "name", "Andrew")
>>> person.name  # accessing instance attribute
"Andrew"
>>> Person.name  # accessing class attribute
"Victor"
>>>

Answer #4

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

Get Solution for free from DataCamp guru