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.

Logical Types<br />

How Logical Arrays Are Used<br />

<strong>MATLAB</strong> has two primary uses for logical arrays:<br />

• “Using Logicals in Conditional Statements” on page 2-35<br />

• “Using Logicals in Array Indexing” on page 2-35<br />

Most mathematics operations are not supported on logical values.<br />

Using Logicals in Conditional Statements<br />

Conditional statements are useful when you want to execute a block of code<br />

only when a certain condition is met. For example, the sprintf command<br />

shown below is valid only if str is a nonempty string. The statement<br />

if ~isempty(str) && ischar(str)<br />

checks for this condition and allows the sprintf to execute only if it is true:<br />

str = 'Hello';<br />

if ~isempty(str) && ischar(str)<br />

sprintf('Input string is ''%s''', str)<br />

end<br />

ans =<br />

Input string is 'Hello'<br />

Using Logicals in Array Indexing<br />

<strong>MATLAB</strong> supports a type of array indexing that uses one array as the index<br />

into another array. For example, array B below indexes into elements 1, 3, 6,<br />

7, and10 of array A:<br />

A = 5:5:50<br />

A =<br />

5 10 15 20 25 30 35 40 45 50<br />

B = [1 3 6 7 10];<br />

2-35

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

Saved successfully!

Ooh no, something went wrong!