Главная

Популярная публикация

Научная публикация

Случайная публикация

Обратная связь

ТОР 5 статей:

Методические подходы к анализу финансового состояния предприятия

Проблема периодизации русской литературы ХХ века. Краткая характеристика второй половины ХХ века

Ценовые и неценовые факторы

Характеристика шлифовальных кругов и ее маркировка

Служебные части речи. Предлог. Союз. Частицы

КАТЕГОРИИ:






Обращение к элементам массива




Элемент массива вызываем, указав имя массива и координаты элемента в скобках. Можно вызвать и часть массива.

>> c1(1,4) ans = -1

>> c1(:,4) («все строки 4-го столбца»)

ans =

-1

-4

>> X=['С' 'А' 'Ж' 'Я' 'В']; Ind=[5 2 1 4]; X(Ind)

ans = ВАСЯ

Все подряд: >> A=[1 2 3; 4 5 6];

>> A(:)

ans =

Поиск последнего элемента

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

>> A(end)

ans = 8

Удаление элементов

>> c1(:,4)=[]; %Удаляем все элементы 4-го столбца введенного выше массива с1

c1 =

1 2 3 -2 -3

4 5 6 -5 -6

>> C=[]; Создаем пустой массив

C =

[]

Удалить одинаковые элементы можно функцией unique(X)

3. Исследование массивов (исследование данных)

Сравнение массивов

>> A=[1 2 3 4; 5 6 7 8]; B=[1.0 2.0 3e0 4; 5 6 7 8];

>> if A==B a='Hurra!'; end

>> a = Hurra!

Определение размеров массивов. Функции length, size

Функции min, max, sort, prod, cumprod, sum, cumsum, mean, median, std

 

Min

C = min(A) returns the smallest elements along different dimensions of an array. If A is a vector, min(A) returns the smallest element in A. If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector containing the minimum element from each column. If A is a multidimensional array, min operates along the first nonsingleton dimension.

 

C = min(A,B) returns an array the same size as A and B with the smallest elements taken from A or B. The dimensions of A and B must match, or they may be scalar.

 

C = min(A,[],dim) returns the smallest elements along the dimension of A specified by scalar dim. For example, min(A,[],1) produces the minimum values along the first dimension (the rows) of A.

[C,I] = min(...) finds the indices of the minimum values of A, and returns them in output vector I. If there are several identical minimum values, the index of the first one found is returned.

 

B=[1 2; 3 4];

>> bb=min(B)

bb= 1 2

>> bbb=min(min(B)) = 1 %«Глобальный» минимум

>> [b1,k]=min(B^-1)

b1 = -2.0000 -0.5000

k = 1 2

 

Mean

Average or mean value of array

M = mean(A) returns the mean values of the elements along different dimensions of an array.

If A is a vector, mean(A) returns the mean value of A. If A is a matrix, mean(A) treats the columns of A as vectors, returning a row vector of mean values. If A is a multidimensional array, mean(A) treats the values along the first non-singleton dimension as vectors, returning an array of mean values.

M = mean(A,dim) returns the mean values for elements along the dimension of A specified by scalar dim. For matrices, mean(A,2) is a column vector containing the mean value of each row.

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

mean(A) =

3.0000 4.5000 6.0000

 

mean(A,2) =

2.0000

4.0000

6.0000

6.0000

Пусть объективно существующая случайная величина X в результате опытов предстала в виде значений . Вектор выборка величины X. Выборочным средним называется случайная величина

.

Выборочная дисперсия — это случайная величина

.

Несмещённая (исправленная) дисперсия — это случайная величина

.

Величина назыв. среднеквадратическим отклонением выборки, величина - среднеквадратическим отклонением при ее несмещенной оценке, или стандартным отклонением.

Mode

Most frequent values in array

M = mode(X) for vector X computes the sample mode M, (i.e., the most frequently occurring value in X). If X is a matrix, then M is a row vector containing the mode of each column of that matrix. If X is an N-dimensional array, then M is the mode of the elements along the first nonsingleton dimension of that array.

When there are multiple values occurring equally frequently, mode returns the smallest of those values. For complex inputs, this is taken to be the first value in a sorted list of values.

 

M = mode(X, dim) computes the mode along the dimension dim of X.

[M,F] = mode(X,...) also returns array F, each element of which represents the number of occurrences of the corresponding element of M. The M and F output arrays are of equal size.

[M,F,C] = mode(X,...) also returns cell array C, each element of which is a sorted vector of all values that have the same frequency as the corresponding element of M.

 

X = [3 3 1 4; 0 0 1 1; 0 1 2 4] =

3 3 1 4

0 0 1 1

0 1 2 4

 

mode(X) =

0 0 1 4

mode(X, 2) =

 

Пример из Help’а Построение гистограммы

>> randn('state', 0); % Reset the random number generator Переустановка генератора Марсальи

>> y = randn(1000,1); % Y = randn(m,n) returns an m-by-n matrix of pseudorandom values drawn from a

% normal distribution with mean 0 and standard deviation 1

>> edges = -6:.25:6; % Массив промежутков

>> [n,bin] = histc(y,edges);

>> m = mode(bin)

m = 25

>> edges([m, m+1])

ans = 0 0.2500

>> hist(y,edges+.125)

 

n = histc(x,edges) counts the number of values in vector x that fall between the elements in the edges vector (which must contain monotonically nondecreasing values). n is a length(edges) vector containing these counts.

 

 

median (середина)

Median value of array

M = median(A) returns the median values of the elements along different dimensions of an array. If A is a matrix, median(A) treats the columns of A as vectors, returning a row vector of median values.

M = median(A,dim) returns the median values for elements along the dimension of A specified by scalar dim.

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

median(A) =

 

4 5 7 7

median(A,2) =

 

Std

Standard deviation

Syntax

s = std(X)

s = std(X,flag)

s = std(X,flag,dim)

Definition

There are two common textbook definitions for the standard deviation s of a data vector X:

(1); (2).

where and is the number of elements in the sample. The two forms of the equation differ only in versus in the divisor.

s = std(X), where X is a vector, returns the standard deviation using (1) above. The result s is the square root of an unbiased estimator of the variance of the population (несмещенная оценка дисперсии совокупности) from which X is drawn, as long as X consists of independent, identically distributed samples (выборок).

If X is a matrix, std(X) returns a row vector containing the standard deviation of the elements of each column of X. If X is a multidimensional array, std(X) is the standard deviation of the elements along the first nonsingleton dimension of X (singleton – одиночка; одноразмерный).

s = std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1) returns the standard deviation using (2) above, producing the second moment of the set of values about their mean.

s = std(X,flag,dim) computes the standard deviations along the dimension of X specified by scalar dim. Set flag to 0 to normalize Y by n-1; set flag to 1 to normalize by n.

 

 

Var

Variance (дисперсия)

V = var(X) returns the variance of X for vectors. For matrices, var(X)is a row vector containing the variance of each column of X. For N-dimensional arrays, var operates along the first nonsingleton dimension of X. The result V is an unbiased estimator of the variance of the population from which X is drawn, as long as X consists of independent, identically distributed samples.

var normalizes V by N-1 if N>1, where N is the sample size. This is an unbiased estimator of the variance of the population from which X is drawn, as long as X consists of independent, identically distributed samples. For N=1, V is normalized by N.

V = var(X,1) normalizes by N and produces the second moment of the sample about its mean.var(X,0) is equivalent to var(X).

 

V = var(X,w) computes the variance using the weight vector w. The length of w must equal the length of the dimension over which var operates, and its elements must be nonnegative. The elements of w must be positive. var normalizes w to sum of 1.

 

Логический поиск нужного элемента. Функция find.

Find

Find indices and values of nonzero elements

ind = find(X) locates all nonzero elements of array X, and returns the linear indices of those elements in vector ind. If X is a row vector, then ind is a row vector; otherwise, ind is a column vector. If X contains no nonzero elements or is an empty array, then ind is an empty array.

ind = find(X, k) or ind = find(X, k, 'first') returns at most the first k indices corresponding to the nonzero entries of X. k must be a positive integer, but it can be of any numeric data type.

ind = find(X, k, 'last') returns at most the last k indices corresponding to the nonzero entries of X.

[row,col] = find(X,...) returns the row and column indices of the nonzero entries in the matrix X. This syntax is especially useful when working with sparse matrices. If X is an N-dimensional array with N > 2, col contains linear indices for the columns. For example, for a 5-by-7-by-3 array X with a nonzero element at X(4,2,3), find returns 4 in row and 16 in col. That is, (7 columns in page 1) + (7 columns in page 2) + (2 columns in page 3) = 16.

[row,col,v] = find(X,...) returns a column or row vector v of the nonzero entries in X, as well as row and column indices. If X is a logical expression, then v is a logical array. Output v contains the non-zero elements of the logical array obtained by evaluating the expression X. For example,

 

A= magic(4)

A =

16 2 3 13

5 11 10 8

9 7 6 12

4 14 15 1

 

[r,c,v]= find(A>10);

 

r', c', v'

ans =

1 2 4 4 1 3

ans =

1 2 2 3 4 4

ans =

1 1 1 1 1 1

 

Here the returned vector v is a logical array that contains the nonzero elements of N where

N=(A>10)

Example 1

X = [1 0 4 -3 0 0 0 8 6];

indices = find(X)

returns linear indices for the nonzero entries of X.

indices =

1 3 4 8 9

 

Example 2

You can use a logical expression to define X. For example,

find(X > 2)

returns linear indices corresponding to the entries of X that are greater than 2.

ans = 3 8 9

Example 3

X = [3 2 0; -5 0 7; 0 0 1];

[r,c,v] = find(X)

returns a vector of row indices of the nonzero entries of X

r =

a vector of column indices of the nonzero entries of X

c =

and a vector containing the nonzero entries of X.

v =

-5

Example 4

The expression

[r,c,v] = find(X>2)

returns a vector of row indices of the nonzero entries of X

r =

a vector of column indices of the nonzero entries of X

c =

and a logical array that contains the non zero elements of N where N=(X>2).

v =

Recall that when you use find on a logical expression, the output vector v does not contain the nonzero entries of the input array. Instead, it contains the nonzero values returned after evaluating the logical expression.

Example 5

x = [11 0 33 0 55]';

find(x)

ans =

find(x == 0)

ans =

find(0 < x & x < 10*pi)

ans =

Example 6

M =

8 1 6

3 5 7

4 9 2

find(M > 3, 4)

returns the indices of the first four entries of M that are greater than 3.

ans =

Example 7

If X is a vector of all zeros, find(X) returns an empty matrix. For example,

indices = find([0;0;0])

indices = Empty matrix: 0-by-1

All

Determine whether all array elements are nonzero

B = all(A) tests whether all the elements along various dimensions of an array are nonzero or logical 1 (true).

If A is a vector, all(A) returns logical 1 (true) if all the elements are nonzero and returns logical 0 (false) if one or more elements are zero.

If A is a matrix, all(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's.

If A is a multidimensional array, all(A) treats the values along the first nonsingleton dimension as vectors, returning a logical condition for each vector.

B = all(A, dim) tests along the dimension of A specified by scalar dim.

, all(A,1) = (1 1 0), all(A,2) = /

 

Any

Determine whether any array elements are nonzero

B = any(A) tests whether any of the elements along various dimensions of an array is a nonzero number or is logical 1 (true). any ignores entries that are NaN (Not a Number).

If A is a vector, any(A) returns logical 1 (true) if any of the elements of A is a nonzero number or is logical 1 (true), and returns logical 0 (false) if all the elements are zero.

If A is a matrix, any(A) treats the columns of A as vectors, returning a row vector of logical 1's and 0's.

If A is a multidimensional array, any(A) treats the values along the first nonsingleton dimension as vectors, returning a logical condition for each vector.

B = any(A,dim) tests along the dimension of A specified by scalar dim.

Example 1 – Reducing a Logical Vector to a Scalar Condition

Given A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69]

 

then B = (A < 0.5) returns logical 1 (true) only where A is less than one half:

0 0 1 1 1 1 0

 

The any function reduces such a vector of logical conditions to a single condition. In this case, any(B) yields logical 1. This makes any particularly useful in if statements:

 

if any(A < 0.5)do something

end

where code is executed depending on a single condition, not a vector of possibly conflicting conditions.

Example 2 – Reducing a Logical Matrix to a Scalar Condition

Applying the any function twice to a matrix, as in any(any(A)), always reduces it to a scalar condition.

any(any(eye(3)))

ans = 1

 

Example 3 – Testing Arrays of Any Dimension

You can use the following type of statement on an array of any dimensions. This example tests a 3-D array to see if any of its elements are greater than 3:

 

x = rand(3,7,5) * 5;

 

any(x(:) > 3)

ans =

or less than zero:

any(x(:) < 0)

ans = 0

 

 






Не нашли, что искали? Воспользуйтесь поиском:

vikidalka.ru - 2015-2024 год. Все права принадлежат их авторам! Нарушение авторских прав | Нарушение персональных данных