如何在MATLAB中查找非零元素的索引和值?
MATLAB是一个强大的工具,可以执行与数组和矩阵相关的运算和计算。在MATLAB中,数组或矩阵是一种用于存储数值数据的数据结构。存储在数组或矩阵中的每个值称为元素。元素在数组或矩阵中的位置称为元素的索引。
MATLAB提供了一个内置函数“find”,它使我们能够找到给定数组或矩阵中非零元素的索引和值。但是,在MATLAB中,我们也可以使用循环机制(即,不使用“find”函数)来查找非零元素的值和索引。
下面解释了这两种使用MATLAB在数组中查找非零元素的值和索引的方法。
(1). 不使用“find”函数查找非零元素的索引和值
在MATLAB中,我们可以不使用“find”函数来查找数组或矩阵中非零元素的索引和值。为此,我们迭代遍历矩阵的元素以检查它们是否为零。如果元素是非零值,则循环将提取其索引和值并存储在另一个数组中。
示例
让我们来看一个例子,以实际了解不使用“find”函数查找非零元素索引和值的过程。
% MATLAB program to find indices and values of non-zero elements without using "find" function
% Create an example matrix
X = [0, 5, 0, 3; 0, 2, 1, 0; 2, 0, 7, 0; 1, 0, 3, 7];
% Create an empty array to store indices of non-zero elements
I = [];
% Create an empty array to store values of non-zero elements
V = [];
% Determine the size of the input matrix
[m, n] = size(X);
% Iterate a loop through elements of the matrix
for i = 1 : m
for j = 1 : n
if X(i, j) ~= 0 % Check if the element is non-zero
% Store the indices of non-zero elements
I = [I; i, j];
% Store the values of non-zero elements
V = [V; X(i, j)];
end
end
end
% Display the results
disp('Input matrix:');
disp(X);
disp('Indices of non-zero elements:');
disp(I);
disp('Values of non-zero elements:');
disp(V);
输出
Input matrix:
0 5 0 3
0 2 1 0
2 0 7 0
1 0 3 7
Indices of non-zero elements:
1 2
1 4
2 2
2 3
3 1
3 3
4 1
4 3
4 4
Values of non-zero elements:
5
3
2
1
2
7
1
3
7
代码解释
在此MATLAB代码中,我们首先创建一个示例矩阵“X”。然后,我们创建两个空数组,一个用于存储非零元素的索引“I”,另一个用于存储非零元素的值“V”。
之后,我们确定矩阵或数组的大小以定义合适的循环。然后,我们指定“for”循环,该循环查找输入矩阵中的非零元素,并将它们的索引和值分别存储在数组“I”和“V”中。
最后,我们显示输入矩阵、非零元素的索引及其值。
(2). 使用“find”函数查找非零元素的索引和值
在MATLAB中,“find”函数是一个内置函数,用于查找数组或矩阵中非零元素的索引和值。
语法
要查找非零元素的索引和值,我们可以使用“find”函数的以下语法:
[row_ind, col_ind, V] = find(X);
这里,变量“row_ind”存储非零元素的行索引,“col_ind”存储非零元素的列索引,“V”存储非零元素的值,而X是输入矩阵。
让我们来看一个例子,了解如何实现MATLAB代码以使用“find”函数查找数组中非零元素的索引和值。
示例
% MATLAB code to find indices and values of non-zero elements using "find" function
% Create an input matrix
X = [0, 5, 0, 3; 0, 2, 1, 0; 2, 0, 7, 0; 1, 0, 3, 7];
% Find indices and values of nonzero elements
[row_ind, col_ind, V] = find(X);
% Display the results
disp('Input matrix:');
disp(X);
disp('Row indices of non-zero elements:');
disp(row_ind);
disp('Column indices of non-zero elements:');
disp(col_ind);
disp('Values of non-zero elements:');
disp(V);
输出
Input matrix:
0 5 0 3
0 2 1 0
2 0 7 0
1 0 3 7
Row indices of non-zero elements:
3
4
1
2
2
3
4
1
4
Column indices of non-zero elements:
1
1
2
2
3
3
3
4
4
Values of non-zero elements:
2
1
5
2
1
7
3
3
7
代码解释
在此MATLAB示例中,首先,我们创建一个包含零和非零元素的输入矩阵“X”。然后,我们调用“find”函数来确定非零元素的索引和值。非零元素的索引存储在向量“row_ind”和“col_ind”中,值存储在向量“V”中。
最后,我们显示输入矩阵、非零元素的行索引和列索引以及非零元素的值。
结论
在本教程中,我解释了两种使用MATLAB查找数组或矩阵中非零元素索引和值的不同方法。在第一种方法中,我们使用“for”循环查找数组中的非零元素,然后查找它们的索引和值。在第二种方法中,我们使用内置函数“find”来确定非零元素的索引和值。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP