前面,给各位介绍了Matlab中使用length函数获取数组的最大长度值,感兴趣的可以参考:《Matlab使用length函数获取数组最大长度》。今天,再给大家介绍一个numel函数,可以用于获取组成数组的元素个数。本文,主要介绍numel函数的常见用法、语法说明、三维矩阵中元素的数目、字符串数组、元胞数组中的元素数、表格中元素的数目等。

下面,首先给出Matlab中关于numel函数的帮助文档如下:
>> help numel
numel Number of elements in an array or subscripted array expression.
N = numel(A) returns the number of elements, N, in array A, equivalent
to PROD(SIZE(A)).常见用法
n = numel(A)语法说明
n = numel(A) 返回数组 A 中的元素数目 n 等同于 prod(size(A))。
三维矩阵中元素的数目
创建一个 4×4×2 矩阵。
A = magic(4);
A(:,:,2) = A'输出结果如下:
A(:,:,1) =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
A(:,:,2) =
16 5 9 4
2 11 7 14
3 10 6 15
13 8 12 1numel计算出矩阵中有 32 个元素。
n = numel(A)输出结果如下:
n = 32字符串数组
创建一个字符串数组,并计算数组中的元素数。
A = ["a" "b" "c"; "d" "e" "f"]
Matlab 2016中,不能使用双引号引入字符,需要使用单引号,代码如下:
A = ['a' 'b' 'c'; 'd' 'e' 'f']输出结果如下:
A =
abc
def
n = numel(A)输出结果如下:
n =
6元胞数组中的元素数
创建字符向量元胞数组。
A = {'dog','cat','fish','horse'};numel计算出数组中有 4 个元素。
n = numel(A)输出结果如下:
n =
4表格中元素的数目
创建一个表,其中包含列出五位病患信息的四个变量。
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
A = table(Age,Height,Weight,BloodPressure,'RowNames',LastName)输出结果如下:
A =
Age Height Weight BloodPressure
___ ______ ______ _____________
Smith 38 71 176 124 93
Johnson 43 69 163 109 77
Williams 38 64 131 125 83
Jones 40 67 133 117 75
Brown 49 64 119 122 80 计算表格中的元素数目。
n = numel(A)输出结果如下:
n =
20numel 返回一个值,等同于对应于 5 行和 4 个变量的 prod(size(A))。
转载文章,原文出处:MathWorks官网,由古哥整理发布
如若转载,请注明出处:https://iymark.com/articles/2459.html

微信扫一扫
支付宝扫一扫


评论列表(2条)
不孬
想念古哥的第一天,One Day~