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