MATLAB Programming

MATLAB Programming MATLAB Programming

cda.psych.uiuc.edu
from cda.psych.uiuc.edu More from this publisher
23.06.2015 Views

2 Data Types A(B) ans = 5 15 30 35 50 In this case, the numeric values of array B designate the intended elements of A. Another type of array index, a logical index, designates the elements of A based on their position in the indexing array, B. Inthismasking type of operation, every true element in the indexing array is treated as a positional index into the array being accessed. Logical Indexing Example 1. This next example creates logical array B that satisfies the condition A > 0.5, and uses the positions of ones in B to index into A. Thisiscalledlogical indexing: A = rand(5); B = A > 0.5; A(B) = 0 A = 0.2920 0.3567 0.1133 0 0.0595 0 0.4983 0 0.2009 0.0890 0.3358 0.4344 0 0.2731 0.2713 0 0 0 0 0.4091 0.0534 0 0 0 0.4740 A simpler way to express this is A(A > 0.5) = 0 Logical Indexing Example 2. The next example highlights the location of the prime numbers in a magic square using logical indexing to set the nonprimes to 0: A = magic(4) A = 16 2 3 13 5 11 10 8 9 7 6 12 2-36

Logical Types 4 14 15 1 B = isprime(A) B = 0 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 A(~B) = 0; % Logical indexing A A = 0 2 3 13 5 11 0 0 0 7 0 0 0 0 0 0 Identifying Logical Arrays This table shows the commands you can use to determine whether or not an array x is logical. The last function listed, cellfun, operates on cell arrays, which you can read about in the section “Cell Arrays” on page 2-94. Command Operation whos(x) Display value and data type for x. islogical(x) isa(x, 'logical') class(x) cellfun('islogical', x) Return true if array is logical. Return true if array is logical. Return string with data type name. Check each cell array element for logical. 2-37

Logical Types<br />

4 14 15 1<br />

B = isprime(A)<br />

B =<br />

0 1 1 1<br />

1 1 0 0<br />

0 1 0 0<br />

0 0 0 0<br />

A(~B) = 0;<br />

% Logical indexing<br />

A<br />

A =<br />

0 2 3 13<br />

5 11 0 0<br />

0 7 0 0<br />

0 0 0 0<br />

Identifying Logical Arrays<br />

This table shows the commands you can use to determine whether or not an<br />

array x is logical. The last function listed, cellfun, operates on cell arrays,<br />

which you can read about in the section “Cell Arrays” on page 2-94.<br />

Command<br />

Operation<br />

whos(x) Display value and data type for x.<br />

islogical(x)<br />

isa(x, 'logical')<br />

class(x)<br />

cellfun('islogical', x)<br />

Return true if array is logical.<br />

Return true if array is logical.<br />

Return string with data type name.<br />

Check each cell array element for logical.<br />

2-37

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

Saved successfully!

Ooh no, something went wrong!