Open In App

Comparing Two Cell Arrays of Strings of Different Sizes in MATLAB

Last Updated : 12 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

MATLAB is a high-performance language that is used for matrix manipulation, performing technical computations, graph plottings, etc. It stands for Matrix Laboratory.

  • Cell Array: A cell Array in MATLAB is a data type that can store any type of data. Data is stored in cells in a cell array. It is initialized using { } i.e. curly braces. E.g. A = { 5, “gfg” , 7.2 } 
  • Accessing a Cell Array: To access a cell array we use curly braces and its index. Indexing starts with 1. E.g. A = { 5, “gfg” , 7.2 }

Now A{1} will return 5, A{2} will return “gfg” and A{3} will return 7.2

 

Comparing Two Cell Arrays of Strings:

ismember(a,b): It compares the ‘a’ and ‘b’ cell arrays and returns a logical array which has 0 and 1 of size same as of cell array ‘a’. It returns 0 if the element in cell array ‘a’ is not present in cell array ‘b’. If it is present it returns 1.

setdiff(a,b): It compares the ‘a’ and ‘b’ cell arrays and returns an array that has elements from cell array ‘a’ that are not there in cell array ‘b’. 

Syntax:

ismember(a,b)

setdiff(a,b)

Example 1 : 

Matlab




% MATLAB code 
A = { 'gfg' , 'geeks' , 'geeksforgeeks' };
B = {'gfg' , 'iam' , 'show' };


Output:

ismember(A,B) , 
1×3 logical array = [1, 0, 0] 
setdiff(A,B) , 
1×2 cell array = {'geeks'} {'geeksforgeeks'}

Explanation:

‘gfg’ is present in both the cell arrays hence the first element in the array is 1. The other two are 0 because ‘geeks’ and ‘geeks for geeks’ both are not present in the cell Array B. setdiff is returning cell array {‘geeks’} {‘geeksforgeeks’} because they are the elements from the cell Array A that are not present in cell Array B.

Example 2:

Matlab




% Cell Array A
A = { 'gfg' , 'geeks' , 'geeksforgeeks' }
  
%Cell Array B
B = {'gfg' , 'iam' , 'show' }
  
% ismember function
ismember(A,B)
  
% setdiff function
setdiff(A,B)


Output:

1   0   0
{'geeks'}    {'geeksforgeeks'}

Input

 

Example 3: 

Matlab




% Cell Array A
A = { 'program' , 'matlab' }
  
%Cell Array B
B = { 'matlab', 'programming' , 'gfg'}
  
% ismember function
ismember(A,B)
  
% setdiff function
setdiff(A,B)


Output:

0   1
{'program'}

input

output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads