python 对角阵_numpy创建单位矩阵和对角矩阵的实例

本文介绍了如何在Python中使用numpy库创建单位矩阵和对角矩阵。通过numpy的identity()函数可以生成单位矩阵,而eye()函数则用于创建对角矩阵。示例代码展示了如何设置矩阵大小、对角线元素以及数据类型。
摘要由CSDN通过智能技术生成

在学习linear regression时经常处理的数据一般多是矩阵或者n维向量的数据形式,所以必须对矩阵有一定的认识基础。

numpy中创建单位矩阵借助identity()函数。更为准确的说,此函数创建的是一个n*n的单位数组,返回值的dtype=array数据形式。其中接受的参数有两个,第一个是n值大小,第二个为数据类型,一般为浮点型。单位数组的概念与单位矩阵相同,主对角线元素为1,其他元素均为零,等同于单位1。而要想得到单位矩阵,只要用mat()函数将数组转换为矩阵即可。

>>> import numpy as np

>>> help(np.identity)

Help on function identity in module numpy:

identity(n, dtype=None)

Return the identity array.

The identity array is a square array with ones on

the main diagonal.

Parameters

----------

n : int

Number of rows (and columns) in `n` x `n` output.

dtype : data-type, optional

Data-type of the output. Defaults to ``float``.

Returns

-------

out : ndarray

`n` x `n` array with its main diagonal set to one,

and all other elements 0.

Examples

--------

>>> np.identity(3)

array([[ 1., 0., 0.],

[ 0., 1., 0.],

[ 0., 0., 1.]])

>>> np.identity(5)

array([[1., 0., 0., 0., 0.],

[0., 1., 0., 0., 0.],

[0., 0., 1., 0., 0.],

[0., 0., 0., 1., 0.],

[0., 0., 0., 0., 1.]])

>>> A = np.mat(np.identity(5))

>>> A

matrix([[1., 0., 0., 0., 0.],

[0., 1., 0., 0., 0.],

[0., 0., 1., 0., 0.],

[0., 0., 0., 1., 0.],

[0., 0., 0., 0., 1.]])

矩阵的运算中还经常使用对角阵,numpy中的对角阵用eye()函数来创建。eye()函数接受五个参数,返回一个单位数组。第一个和第二个参数N,M分别对应表示创建数组的行数和列数,当然当你只设定一个值时,就默认了N=M。第三个参数k是对角线指数,跟diagonal中的offset参数是一样的,默认值为0,就是主对角线的方向,上三角方向为正,下三角方向为

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值