如何在 MATLAB 中查找数组中数字的位置?
数组或矩阵中数字的位置也称为该数字在数组或矩阵中的索引。在 MATLAB 中,数组是一索引的,这意味着数组第一个元素的索引将是“1”,第二个元素的索引将是“2”,依此类推。
为了查找数组中数字的位置,MATLAB 提供了多种方法。在这里,我们将介绍两种常用的方法,它们是
使用“find”函数。
使用循环机制。
让我们探索使用 MATLAB 查找数组中数字位置的这些方法。
方法 1 - 使用“find”函数查找数组中数字的位置
“find”函数是 MATLAB 中的一个内置函数,它可以帮助我们确定数组或矩阵中特定数字的位置或索引。
语法
num_position = find(A == number);
这里,A 是数组,“number”是在数组中要确定其位置的数字。
让我们看一个示例来了解此函数在确定数组中数字位置时的实现。
示例
% MATLAB code to find the position of a number in an array
% Create a sample array
A = [10, 15, 20, 25, 30, 35, 15, 30, 15];
% Specify the number whose position to be determined
number = 15;
% Determine the position of the number in the array
num_position = find(A == number);
% Display the array and position of the specified number
disp('Input array A:');
disp(A);
disp(['Specified number: ', num2str(number)]);
disp(['Position of ', num2str(number), 'in the array A is: ' num2str(num_position)]);
输出
Input array A:
10 15 20 25 30 35 15 30 15
Specified number: 15
Position of 15 in the array A is: 2 7 9
因此,这就是关于使用“find”函数查找数组中数字位置的所有内容。
现在让我们讨论如何使用循环来实现相同的功能。
方法 2 - 使用循环查找数组中数字的位置
在这种方法中,我们必须创建一个循环并遍历输入数组以查找数组中指定数字的位置。
让我们借助 MATLAB 中的一个示例来了解这种确定数组中数字位置的方法。
示例
% MATLAB code to determine the position of a number in an array using a loop
% Create a sample array
A = [10, 15, 20, 25, 30, 35, 15, 30, 15];
% Specify the number whose position to be determined
number = 15;
% Create an empty array to hold the positions of the number
num_position = [];
% Create a loop and iterate it through the array to find the positions
for i = 1:length(A)
if A(i) == number
num_position = [num_position, i];
end
end
% Display the input array, number, and its positions
disp('Input array A:');
disp(A);
disp(['Specified number: ', num2str(number)]);
disp(['Position of ', num2str(number), 'in the array A is: ' num2str(num_position)]);
输出
Input array A:
10 15 20 25 30 35 15 30 15
Specified number: 15
Position of 15in the array A is: 2 7 9
结论
这就是关于使用 MATLAB 查找数组中数字位置的所有内容。在本教程中,我们讨论了两种常用的查找数组或矩阵中给定数字的位置或索引的方法。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP