如何在 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