创建一个平方单位矩阵 [英] Creating a square identity matrix

查看:236
本文介绍了创建一个平方单位矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个称为identity的函数,该函数创建一个平方的单位矩阵,该矩阵的元素为0,对角线上的元素(从左上到右下)的值为1.行和列索引相同的元素中的(1,1),(2,2)等

Write a function called identity that creates a square identity matrix, which is a matrix whose elements are 0 except for the elements on the diagonal (from top left to bottom right) which have a value of 1. The diagonal consists of those elements whose row and column indexes are the same: (1,1), (2,2), etc.

该函数采用一个正整数输入参数(即矩阵的大小),并将矩阵本身作为输出参数返回.

The function takes one positive integer input argument, which is the size of the matrix, and returns the matrix itself as an output argument.

例如,identity(4)必须返回4×4身份矩阵.

For example, identity(4) must return a 4-by-4 identity matrix.

不允许使用内置的eyediag函数.

You are not allowed to use the built-in eye or diag functions.

(提示:您可以使用单个索引索引到矩阵中,MATLAB会使用列优先顺序将其当作向量来处理.)

(Hint: you can index into a matrix with a single index and MATLAB will handle it as if it was a vector using column-major order.)

推荐答案

让我们用两行简单的代码完成操作,并且不使用zeros ...第一行创建一个n x n矩阵,其中所有元素均为0.之后,您可以按照提示说出元素的含义.单位矩阵中两者之间的距离为n+1.这样,您就可以将提到的距离写到末尾.

Let's do it in two simple lines and without zeros... The first line creates a n x n matrix where all elements are 0. After you can (as your hint says) address the elements with a single argument. The distance between the ones in the identity matrix are n+1. This way you write the ones with the mentioned distance until the end.

function out = identity(n)
    out(n,n)       = 0;
    out(1:n+1:end) = 1;
end

这篇关于创建一个平方单位矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆