Matlab

strcmp() Function in Matlab

A popular programming language and environment for numerical computing and data analysis is called MATLAB. Among its many built-in functions, the strcmp() function stands out as a useful tool for comparing strings. In this article, we will explore the syntax and provide examples to demonstrate the functionality of the strcmp() function in MATLAB.

The strcmp() Function in Matlab

When comparing two strings in MATLAB, the strcmp() function is used to determine whether the strings are equal. It returns a logical value that represents the outcome of the comparison and can be either true or false. The following is the strcmp() function’s general syntax:

compare = strcmp(string1, string2)

 

Here, string1 and string2 represent the two strings that you want to compare, and the compare variable will hold the boolean value of either true or false based on the comparison.

Example 1: Basic String Comparison

Here is a simple example to compare two strings and see how strcmp() works:

string1 = 'Sam';
string2 = 'Sam';

compare = strcmp(string1, string2);
disp(compare);

 

In this example, both string1 and string2 contain the same string, Sam and the strcmp() function compares them and returns a logical value of 1 (true) since the strings are equal:

Example 2: Case-Sensitive Comparison

The strcmp() also considers the case of the strings when performing the comparison, so here is an example code that compares two strings that differ only in case:

string1 = 'Sam';
string2 = 'sam';
compare = strcmp(string1, string2);
disp(compare);

 

Here, the strings Sam and sam are not the same because the strcmp() function is case-sensitive, thus the function returns a logical value of 0 (false).

Example 3: Comparing Cell Arrays of Strings

The strcmp() function can also handle cell arrays of strings, allowing you to compare multiple strings simultaneously, below is a demonstration:

fruits_str1 = {'apple', 'banana', 'orange'};
fruits_str2 = {'banana', 'cherry', 'orange'};

compare = strcmp(fruits_str1, fruits_str2);
disp(compare);

 

Here, we have two cell arrays of strings, fruits_str1, and fruits_str2, with three elements each. The strcmp() function compares the corresponding strings from both arrays and returns a logical array with values 0 and 1. It indicates that the first two strings are not the same, while the third string is equal:

Conclusion

The strcmp() function in MATLAB serves as a valuable tool for comparing strings. By utilizing this function, you can easily determine if two strings are equal or not. Remember that strcmp() is case-sensitive, so it considers differences in uppercase and lowercase characters. Moreover, it can also handle cell arrays of strings, allowing for efficient comparisons of multiple strings at once.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.