创建一个平方单位矩阵

编程入门 行业动态 更新时间:2024-10-26 16:22:44
本文介绍了创建一个平方单位矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

编写一个称为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

更多推荐

创建一个平方单位矩阵

本文发布于:2023-11-29 23:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   创建一个   单位

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!