How to apply a logarithm to a matrix with numpy in python ?

Published: July 18, 2020

Tags: Python; Numpy;

DMCA.com Protection Status

Examples of how to apply a logarithm to a matrix with numpy in python :

Using the numpy function log()

To apply a logarithm to a matrix, a solution is to use numpy.log, illustration:

import numpy as np
import math

A = np.array((math.e))

print(A)

A = np.log(A)

print(A)

returns respectively:

2.718281828459045

and

1.0

Another example:

A = np.arange(1.0,10.0,1.0)

A = np.log(A)

returns

[1. 2. 3. 4. 5. 6. 7. 8. 9.]

and

[0.         0.69314718 1.09861229 1.38629436 1.60943791 1.79175947

1.94591015 2.07944154 2.19722458]

Plot a figure using a logarithm scale with matplotlilb

Note: To plot a figure using a logarithm scale with matplotlilb , a solution is to use ax.set_yscale('log'), example:

from pylab import figure, cm

import matplotlib.pyplot as plt

x = np.arange(0.0,10.0,0.1)

y = np.exp(x)

fig = figure(num=None, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')

plt.plot(x,y)

plt.grid(True,which="both", linestyle='--')

plt.savefig("log_fig_01.png", bbox_inches='tight')

plt.show()

How to apply a logarithm to a matrix with numpy in python ?
How to apply a logarithm to a matrix with numpy in python ?

fig = figure(num=None, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')

ax = fig.add_subplot(1, 1, 1)

plt.plot(x,y)

ax.set_yscale('log')

plt.grid(True,which="both", linestyle='--')

plt.savefig("log_fig_02.png", bbox_inches='tight')

plt.show()

How to apply a logarithm to a matrix with numpy in python ?
How to apply a logarithm to a matrix with numpy in python ?

References

Image

of