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.

2 Data Types<br />

A(B)<br />

ans =<br />

5 15 30 35 50<br />

In this case, the numeric values of array B designate the intended elements<br />

of A.<br />

Another type of array index, a logical index, designates the elements of A<br />

based on their position in the indexing array, B. Inthismasking type of<br />

operation, every true element in the indexing array is treated as a positional<br />

index into the array being accessed.<br />

Logical Indexing Example 1. This next example creates logical array B<br />

that satisfies the condition A > 0.5, and uses the positions of ones in B to<br />

index into A. Thisiscalledlogical indexing:<br />

A = rand(5);<br />

B = A > 0.5;<br />

A(B) = 0<br />

A =<br />

0.2920 0.3567 0.1133 0 0.0595<br />

0 0.4983 0 0.2009 0.0890<br />

0.3358 0.4344 0 0.2731 0.2713<br />

0 0 0 0 0.4091<br />

0.0534 0 0 0 0.4740<br />

A simpler way to express this is<br />

A(A > 0.5) = 0<br />

Logical Indexing Example 2. The next example highlights the location<br />

of the prime numbers in a magic square using logical indexing to set the<br />

nonprimes to 0:<br />

A = magic(4)<br />

A =<br />

16 2 3 13<br />

5 11 10 8<br />

9 7 6 12<br />

2-36

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

Saved successfully!

Ooh no, something went wrong!