Creating Matrices

 
  • Arrays may be of various dimensions.
  • A 2D array is a matrix.
  • A 1D array is called a vector.
% row vector
r1 = [1,2,3,4,5,6]
>>  1  2  3  4  5  6
% comma is optional
r1 = [1 2 3 4 5 6]
>>  1  2  3  4  5  6
% column vector
c1 = [1; 2; 3; 4; 5; 6]
>>
  1
  2
  3
  4
  5
  6
% 2x3 matrix
M = [1 2 3; 4 5 6]
>>
  1   2   3
  4   5   6
% 2x3x2 array
G = rand(2,3,2)
>>
G(:,:,1) =
    0.9841    0.5274    0.9459
    0.7877    0.4144    0.2297
G(:,:,2) =
    0.3961    0.1655    0.0959
    0.5341    0.5611    0.0072

Uniformly Spaced Vectors

Colon Operator:

v = 2:0.2:3
>>  2   2.2   2.4   2.6   2.8   3
v = 2:0.2:3.5   % size of interval 0.2
>>  2   2.2   2.4   2.6   2.8   3   3.2   3.4
v = 2:1:7
>>  2   3   4   5   6   7
v = 2:7
% shortcut for 2:1:7 (size of interval 1)
>>  2   3   4   5   6   7

LINSPACE:

v = linspace(0,10,5)    % Number of elements = 5
>> 0   2.5   5   7.5   10
v = linspace(0,10,4)    % Number of elements = 4
>> 0    3.33333    6.66667   10
v = linspace(0,10)
% row vector of 100 evenly spaced points between 0 and 10