Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
СКМ_Массивы.doc
Скачиваний:
0
Добавлен:
01.07.2025
Размер:
178.69 Кб
Скачать

Скм. Массивы и структуры

1. Создание массивов

Задание перечислением элементов

V1 = [0.1 -3.2 -4.3 0.05] (или V1 = [0.1, -3.2, -4.3, 0.05]). Это одномерный массив (вектор-строка), состоящий из 4 элементов. Элементы массива заключаются в квадр. скобки и отделяются др. от др. пробелами, или запятыми, или пробелами с запятыми. Вектор-столбец задается командой V1=[0.1; 3.2; 4.3; 0.05]

Задаем двумерный массив в виде матрицы из 2 строк и 4 столбцов

X = [1 2 3 4; 5 6 7 8], или

X = [1 2 3 4;

5 6 7 8]

>> A=['Bill' 'John' 'Sesile']; >> A = BillJohnSesile

>> A=['Bill ' 'John ' 'Sesile'] >> A = Bill John Sesile

h='A';

>> whos

Name Size Bytes Class Attributes

A 1x16 32 char

h 1x1 2 char

Рекурсивное задание. Команда B=(-2:2) дает массив целых чисел от -2 до 2:

B = -2 -1 0 1 2.

Команда Х=0:0.2:1 (левая граница промежутка : шаг : правая граница) создает вектор

Х = 0 0.2000 0.4000 0.6000 0.8000 1.0000

Здесь исходный промежуток разделился на 5 равных промежутков с 6 границами. Последний промежуток может быть меньше:

>> X=0:0.21:1

X = 0 0.2100 0.4200 0.6300 0.8400

Создаем 2d матрицу:

>> A=[0:0.2:1; 1:0.2:2]

A =

0 0.2000 0.4000 0.6000 0.8000 1.0000

1.0000 1.2000 1.4000 1.6000 1.8000 2.0000

Равномерный шаг обеспечивается функцией linspace

y = linspace(a,b)generates a row vector y of 100 points linearly spaced between and including a and b.

y = linspace(a,b,n)generates a row vector y of n points linearly spaced between and including a and b

Специальные массивы. Функции zeros, ones, diag, eye, rand, randn

Например, zeros(2,3), ones(2,3), diag(5), eye(4)

diag

Diagonal matrices and diagonals of matrix

X = diag(v,k) when v is a vector of n components, returns a square matrix X of order n+abs(k), with the elements of v on the kth diagonal. k = 0 represents the main diagonal, k > 0 above the main diagonal, and k < 0 below the main diagonal.

>> a=[1 2 3]; B=diag(a,2)

B =

0 0 1 0 0

0 0 0 2 0

0 0 0 0 3

0 0 0 0 0

0 0 0 0 0

>> B=diag(a,-2)

B =

0 0 0 0 0

0 0 0 0 0

1 0 0 0 0

0 2 0 0 0

0 0 3 0 0

X = diag(v) puts v on the main diagonal, same as above with k = 0.

>> A=diag(a) A =

1 0 0

0 2 0

0 0 3

v = diag(X,k) for matrix X, returns a column vector v formed from the elements of the kth diagonal of X.

v = diag(X) returns the main diagonal of X, same as above with k = 0 .

Remarks

diag(diag(X)) is a diagonal matrix.

sum(diag(X)) is the trace of X.

Разреженные матрицы (sparse matricies)

sparse

Create sparse matrix

The sparse function generates matrices in the MATLAB® sparse storage organization.

S = sparse(A) converts a full matrix to sparse form by squeezing out any zero elements. If S is already sparse, sparse(S) returns S.

S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros. Vectors i, j, and s are all the same length. Any elements of s that are zero are ignored, along with the corresponding values of i and j. Any elements of s that have duplicate values of i and j are added together.

Note If any value in i or j is larger than the maximum integer size, 2^31-1, then the sparse matrix cannot be constructed.

To simplify this six-argument call, you can pass scalars for the argument s and one of the arguments i or j—in which case they are expanded so that i, j, and s all have the same length.

S = sparse(i,j,s,m,n) uses nzmax = length(s).

S = sparse(i,j,s) uses m = max(i) and n = max(j). The maxima are computed before any zeros in s are removed, so one of the rows of [i j s] might be [m n 0].

S = sparse(m,n) abbreviates sparse([],[],[],m,n,0). This generates the ultimate sparse matrix, an m-by-n all zero matrix.

rand

Uniformly distributed pseudorandom numbers

Y = rand returns a pseudorandom, scalar value drawn from a uniform distribution on the unit interval.

>> b=rand

b = 0.8147

Y = rand(n) returns an n-by-n matrix of values derived as described above.

Y = rand(m,n) or Y = rand([m n]) returns an m-by-n matrix of the same.

>>R = rand(3,4)

R =

0.8147 0.9134 0.2785 0.9649

0.9058 0.6324 0.5469 0.1576

0.1270 0.0975 0.9575 0.9706

Generate a uniform distribution of random numbers on a specified interval [a,b]. To do this, multiply the output of rand by (b-a), then add a. For example, to generate a 5-by-5 array of uniformly distributed random numbers on the interval [10,50],

a = 10; b = 50; x = a + (b-a) * rand(5)

x =

19.1591 49.8454 10.1854 25.9913 17.2739

46.5335 13.1270 40.9964 20.3948 20.5521

16.0951 27.7071 42.6921 42.0027 15.8216

43.0327 14.2661 44.7478 27.2566 15.4427

31.5337 48.4759 13.3774 46.4259 44.7717

Размножение массивов

repmat

Replicate and tile array

B = repmat(A,m,n) creates a large matrix B consisting of an m-by-n tiling of copies of A. The size of B is [size(A,1)*m, (size(A,2)*n]. The statement repmat(A,n) creates an n-by-n tiling.

B = repmat(A,[m n p...]) produces a multidimensional array B composed of copies of A. The size of B is [size(A,1)*m, size(A,2)*n, size(A,3)*p, ...].

repmat(A,m,n), when A is a scalar, produces an m-by-n matrix filled with A's value and having A's class.

B = repmat(eye(2),3,4)

B =

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

1 0 1 0 1 0 1 0

0 1 0 1 0 1 0 1

Создание новых матриц путем сцепления старых

>> a=[1 2 3; 4 5 6]; b=[-1 -2 -3; -4 -5 -6];

>> c1=[a b]

c1 =

1 2 3 -1 -2 -3

4 5 6 -4 -5 -6

>> c2=[a; b]

c2 =

1 2 3

4 5 6

-1 -2 -3

-4 -5 -6

Конкатенация (сцепление массивов) с помощью функции cat.

C = cat(dim, A, B)concatenates the arrays A and B along dim.

C = cat(dim, A1, A2, A3, A4, ...)concatenates all the input arrays (A1, A2, A3, A4, and so on) along dim.

cat(2, A, B) is the same as [A, B], and cat(1, A, B) is the same as [A; B].

Создаем 3d массив

>> c3=cat(3,a,b)

c3(:,:,1) =

1 2 3

4 5 6

c3(:,:,2) =

-1 -2 -3

-4 -5 -6

Создание новых матриц путем преобразования старых