Accessing and Modifying Matrices

 
% Create a 2x2 matrix
M = [1 2; 3 4]
>>
  1   2
  3   4
% Element-wise square of matrix M
N = M.^2
>>
  1   4
  9  16
% Elements are accessed using parenthesis
% In Matlab/Octave, indices of a matrix starts from 1 (not 0)
N(2,1)
>> 9
% Change the value of an element
N(2,2) = 10
>>
  1   4
  9  10
N(2,3)
>> ERROR: Index exceeds matrix dimensions.

Growing the matrix:

% Undefined elements are initialized with 0
N(2,3) = 15
>>
  1   4   0
  9  10  15
N(3,2) = 7
>>
  1   4   0
  9  10  15
  0   7   0

Linear Indexing:

N is actually stored in memory as a sequence (Column-major order)
1 9 0 4 10 7 0 15 0

N(6)       % >> 7
N(8)       % >> 15
N(10)
>> ERROR: Index exceeds matrix dimensions.
N(10) = 8
% Attempt to grow array along ambiguous dimension.
>> ERROR: Invalid resizing operation or ambiguous assignment..
% put all elements of a matrix in a single column vector
N(:)
>>
   1
   9
   0
   4
  10
   7
   0
  15
   0
size(N(:))
>>  9   1
% max of all elements of a matrix
max(N(:))
>> 15

Multi-element selection:

disp(N)
>>
  1    4    0
  9   10   15
  0    7    0
N([2,3],2)
>>
  10
  7
N([1,3],2)
>>
  4
  7
N([1 3],[1 2])
>>
  1   4
  0   7
N(1:2,1:2)
>>
  1    4
  9   10
N(1:3,2) or N(:,2)
>>
  4
 10
  7
N(5:8)
>>  10    7    0   15

Multi-element modification:

N(:,3) = [1,2,3]
>>
  1    4    1
  9   10    2
  0    7    3
N(:,3) = [3;4;5]
>>
  1    4    3
  9   10    4
  0    7    5
N(:,3) = []
>>
  1    4
  9   10
  0    7
N(:,3) = [5] or N(:,3) = 5
>>
  1    4    5
  9   10    5
  0    7    5
N(:,3) = [1,2]
>> ERROR: Nonconformant arguments..
N(:,5) = 2
>>
  1    4    5    0    2
  9   10    5    0    2
  0    7    5    0    2
N(4,:) = [8]
>>
  1    4    5    0    2
  9   10    5    0    2
  0    7    5    0    2
  8    8    8    8    8
N(3,:) = []
>>
  1    4    5    0    2
  9   10    5    0    2
  8    8    8    8    8

Vectors:

% row vector
r1 = [1 2 3 4]  % or [1, 2, 3, 4]
>>  1  2  3  4
% column vector
c1 = [1; 2; 3; 4]
>>
  1
  2
  3
  4
r1(1,3)     % >> 3
r1(3)       % >> 3
r1(1,6) = 6
>>  1  2  3  4  0  6
r1(9) = 9
>>  1  2  3  4  0  6  0  0  9
c1(4,1)     % >> 4
c1(4)       % >> 4
c1(6,1) = 6
>>
  1
  2
  3
  4
  0
  6
c1(9) = 9
>>
  1
  2
  3
  4
  0
  6
  0
  0
  9

Concatenating Arrays:

M = randi([1,10], 3)
>>
  9     5     1
  2     9     5
  8     6     6
N = randi([11,20], 3)
>>
  18    17    12
  12    20    15
  19    19    18
[M N] or [M, N]
>>
  9     5     1    18    17    12
  2     9     5    12    20    15
  8     6     6    19    19    18
[M; N]
>>
   9     5     1
   2     9     5
   8     6     6
  18    17    12
  12    20    15
  19    19    18