23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Characters and Strings<br />

C =<br />

0<br />

Note For C programmers, this is an important difference between the<br />

<strong>MATLAB</strong> strcmp and C strcmp()functions, where the latter returns 0 if<br />

the two strings are the same.<br />

The first three characters of str1 and str2 areidentical,soinvokingstrncmp<br />

with any value up to 3 returns 1:<br />

C = strncmp(str1, str2, 2)<br />

C =<br />

1<br />

These functions work cell-by-cell on a cell array of strings. Consider the two<br />

cell arrays of strings<br />

A = {'pizza'; 'chips'; 'candy'};<br />

B = {'pizza'; 'chocolate'; 'pretzels'};<br />

Now apply the string comparison functions:<br />

strcmp(A,B)<br />

ans =<br />

1<br />

0<br />

0<br />

strncmp(A,B,1)<br />

ans =<br />

1<br />

1<br />

0<br />

Comparing for Equality Using Operators<br />

You can use <strong>MATLAB</strong> relational operators on character arrays, as long as<br />

the arrays you are comparing have equal dimensions, or one is a scalar. For<br />

example, you can use the equality operator (==) to determine where the<br />

matching characters are in two strings:<br />

2-57

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!