编写一个称为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.
不允许使用内置的eye或diag函数.
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更多推荐
创建一个平方单位矩阵
发布评论