比較MATLAB中不同大小的兩個字串單元陣列
在本文中,我們將學習如何在MATLAB中比較不同大小的兩個字串單元陣列。
字串單元陣列
在MATLAB中,字串單元陣列是一種可以儲存不同型別元素的資料結構。單元陣列的元素用花括號`{}`括起來。
語法
我們可以使用以下語法建立一個字串單元陣列:
A = {'string1', 'string2', 'string3',…'stringN'};
這裡,`A`是一個包含N個字串元素(即`string1`、`string2`……`stringN`)的字串單元陣列。
在MATLAB中,當我們需要儲存和操作不同長度的字串組,或者需要同時操作多個字串時,就會使用字串單元陣列。
比較不同大小的兩個字串單元陣列
MATLAB提供了幾種不同的方法來比較不同大小的兩個字串單元陣列。在本文的以下部分,將藉助MATLAB程式解釋一些比較不同大小的兩個字串單元陣列的重要方法。
使用`ismember`函式比較不同大小的兩個字串單元陣列
我們可以使用MATLAB的內建函式`ismember`來比較兩個單元陣列。`ismember`函式比較兩個單元陣列,並返回一個邏輯陣列,該陣列指示第一個單元陣列的每個元素是否為第二個單元陣列的成員。
語法
要比較兩個單元陣列,我們可以使用以下語法:
C = ismember(A, B);
下面的MATLAB程式演示了使用`ismember`函式比較不同大小的兩個字串單元陣列的實現。
示例
% MATLAB program to demonstrate use of `ismember` function to compare two cell arrays of strings of different sizes
% Create two cell arrays of strings
x = {'Tutorials', 'Point', 'Online', 'Library'};
y = {'Tutorials', 'Point', 'is', 'a', 'Digital', 'Platform'};
% Compare arrays `x` and `y` using `ismember` function
A = ismember(x, y)
% Find the set different between two cell arrays using `setdiff` function
B = setdiff(x, y)
輸出
A =
1x4 logical array
1 1 0 0
B =
1x2 cell array
{'Library'} {'Online'}
解釋
在這個MATLAB程式中,我們首先建立兩個不同大小的字串單元陣列,並將它們儲存在`x`和`y`中。接下來,我們使用`ismember`函式比較這兩個陣列。這個`ismember`函式給出一個邏輯陣列作為輸出,指示陣列`x`中的哪些元素存在於陣列`y`中。然後,我們呼叫`setdiff`函式來顯示存在於陣列`x`中但不存在於陣列`y`中的元素。
使用迴圈方法比較兩個字串單元陣列
我們也可以使用迴圈來比較兩個單元陣列。下面的MATLAB程式演示了這種實現。
示例
% MATLAB program to compare two cell arrays using a loop
% Create two cell arrays of strings
x = {'Tutorials', 'Point', 'Online', 'Library'};
y = {'Tutorials', 'Point', 'is', 'a', 'Digital', 'Platform'};
% Run a loop to compare the corresponding elements of two arrays
for i = 1:min(numel(x), numel(y))
if strcmp(x{i}, y{i})
disp(['Elements at index ', num2str(i), ' are the same.']);
else
disp(['Elements at index ', num2str(i), ' are different.']);
end
end
輸出
Elements at index 1 are the same. Elements at index 2 are the same. Elements at index 3 are different. Elements at index 4 are different.
解釋
在這個MATLAB程式中,我們首先建立兩個包含字串作為元素的單元陣列`x`和`y`。接下來,我們執行一個`for`迴圈來比較這兩個陣列的對應元素。如果兩個單元陣列中特定索引處的字串相等,則程式碼使用`disp`函式顯示訊息“索引'索引號'處的元素相同”。如果索引處的字串不同,則程式碼使用`disp`函式顯示訊息“索引'索引號'處的元素不同”。
因此,這個MATLAB程式比較兩個單元陣列`x`和`y`的對應元素,併為每個索引顯示一條訊息,指示當前索引處的字串是否相同。
結論
因此,這就是我們在MATLAB中比較不同大小的兩個字串單元陣列的方法。在本文的上述部分,我們藉助示例程式說明了兩種最常用的方法來比較不同大小的兩個字串單元陣列。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP