June 26, 2021

Octave Matrices

Matrix/Vector Operations in Octave

A = [1 2; 3 4; 5 6]
A = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ]
A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12] % The ; denotes we are going back to a new row.
B = rand (3, 2);
s=1:6
2:3:15

2 * A
A * B % matrix multiplication
A .* C % element wise multiplication
A .^ 2 % element wise squaring
1 ./ A
A' % A transpose
A' * A
(A')'
max(A)
max(A, [], 1) % column-wise max value
max(A, [], 2) % row-wise max value
max(max(A))
max(A(:))
[r, c] = find(A > 9)
sum(A, 1) % sums up all columns, default
sum(A, 2) % sums up all rows
sum(sum(A .* eye(8)))
sum(sum(A .* flipud(eye(8))))
prediction = theta' * x;

row_vect = [1 5 8]
v=1:6
row_vector = 1:0.1:2
col_vect = [3; 6; 9]
v = mat(1:10)
v = [1;2;3] % Initialize a vector
2 ./ v
-v % -1 * v
v .* v
isvector(x)
log(v)
abs(v)
exp(v)
prod(a)
v + ones(length(v), 1)
sum(a)
prod(a)
max(v)
[val,ind] = max(a)
a < 6
find(a > 4)
floor(a)
ceil(a)
round(x)
inv(M) % inverses of matrix
pinv(A) % inverses of matrices in octave with the pinv(A) function
M^-1 % inverses of matrix
M\eye(size(M)) % inverses of matrix
flipud(A)

ones(2,3)
ones(4)
C = 2 * ones(3,4)
w = zeros(3)
I = eye(2) % Initialize a 2 by 2 identity matrix, is the same as I = [1,0;0,1]
eye(5,5)
flipud(eye(9))
rand(3,3)
randn(1,3)
help rand
A = magic(3)

Indexing starts at 1, in Octave
A(2,3)
B(2,:) % means all elements
C(:,2)
A([1 3], :)
S(3, [1,2])
S(2, [1:3])
B(:)
A(:,3) = [10; 14; 18]
B = [B, [22; 33; 44]];
C = [A B] % concatenating matrices
C = [A; B] % appending matrices

size(A) % dimension of matrix, #rows & # cols
size(A,1) % of rows
size(A,2) % of cols
length(v)
length([1;2;5;7;9])

[m,n] = size(A) % Get the dimension of the matrix A where m = rows and n = columns
dim_A = size(A) % You could also store it this way
dim_v = size(v) % Get the dimension of the vector v
A_23 = A(2,3) % Now let's index into the 2nd row 3rd column of matrix A

add_AB = A + B % See how element-wise addition works
sub_AB = A - B % See how element-wise subtraction works
mult_As = A * s % See how scalar multiplication works
div_As = A / s % Divide A by s
add_As = A + s % What happens if we have a Matrix + scalar?

IA = I*A % What happens when we multiply I*A ?
AI = A*I % How about A*I ?
AB = A*B % Compute A*B
BA = B*A % Is it equal to B*A?
% Note that IA = AI but AB != BA


Related Articles: Matrices/Arrays in MATLAB


1 comment:

  1. Hey! I could have sworn I've been to this site before but after
    reading through some of the post I realized it's new to me.
    Anyways, I'm definitely happy I found it and I'll be
    book-marking and checking back frequently!

    ReplyDelete