Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Одиноков / МиИПиС_асп_13г / MATLAB_R2013a_Выбор.doc
Скачиваний:
33
Добавлен:
15.04.2015
Размер:
4.03 Mб
Скачать

Using Logicals in Array Indexing

A logical array index designates the elements of an array A based on their position in the indexing array, B, not their value. In this masking type of operation, every true element in the indexing array is treated as a positional index into the array being accessed.

In the following example, B is a matrix of logical ones and zeros. The position of these elements in B determines which elements of A are designated by the expression A(B):

A = [1 2 3; 4 5 6; 7 8 9]

A =

1 2 3

4 5 6

7 8 9

B = logical([0 1 0; 1 0 1; 0 0 1]);

B =

0 1 0

1 0 1

0 0 1

A(B)

%{

Здесь A(B) - запрос на значения элементов A, соответствующих логическим единицам матрицы B; ответ - в виде массива-матрицы-вектора-столбца по принципу: A1=A(:); B1=B(:); A1(B1):

ans =

4

2

6

9

%}

The find function can be useful with logical arrays as it returns the linear indices of nonzero elements in B, and thus helps to interpret A(B):

find(B)

ans =

2

4

8

9

Теперь можно найти A(B) как

A(find(B))

ans =

4

2

6

9

Logical Indexing – Example 1

This example creates logical array B that satisfies the condition A > 0.5, and uses the positions of ones in B to index into A:

rng(0,'twister'); % Reset the random number generator (twister -тип генератора)

A = rand(5);

B = A > 0.5; % Поэлементный анализ; результат - массив B (логических единиц и нулей) по форме A.

A(B) = 0 % Здесь не запрос A(B), а присвоение элементам A, большим 0.5, значения 0; ответ - новый массив A:

A =

0 0.0975 0.1576 0.1419 0

0 0.2785 0 0.4218 0.0357

0.1270 0 0 0 0

0 0 0.4854 0 0

0 0 0 0 0

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

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 (~B); ~ - оператор отрицания.

A

A =

0 2 3 13

5 11 0 0

0 7 0 0

0 0 0 0

find(B)

ans =

2

5

6

7

9

13

Logical Indexing with a Smaller Array

In most cases, the logical indexing array should have the same number of elements as the array being indexed into, but this is not a requirement. The indexing array may have smaller (but not larger) dimensions:

A = [1 2 3;4 5 6;7 8 9]

A =

1 2 3

4 5 6

7 8 9

B = logical([0 1 0; 1 0 1])

B =

0 1 0

1 0 1

isequal(numel(A), numel(B)) % Операция сравнения; numel - число элементов массива.

ans =

0

A(B) % Ответ дается для начальных элементов A числом numel(B):

ans =

4

7

8

MATLAB treats the missing elements of the indexing array as if they were present and set to zero, as in array C below:

% Add zeros to indexing array C to give it the same number of

% elements as A.

C = logical([B(:);0;0;0]); % Указание на класс logical необходимо для нулей.

isequal(numel(A), numel(C))

ans =

1

A(C) % Здесь ответ дается для всех элементов A:

ans =

4

7

8