Sunday, October 7, 2007

Vectors

Creating Vectors
a=[1 4 5] % row vector
a=[1;4;5] % column vector
d=[a 6] % add 6 at the end of vector a

a= 1:6 % row vector, value from 1 to 6, increment 1
b= 1:.3:6 % row vector, value from 1 to 6, increment .3

zeros(m,n) % create m x n matrix, all elements are 0
ones(m,n) %
create m x n matrix, all elements are 1
linspace(x1,x2,N) % create a vector of N elements,
% evenly spaced btw x1 and x2
logspace(x1,x2,N)
% create a vector of N elements,
% logarithmically spaced btw x1 and x2


a=[1:2:6 -1 0] gives: 1 3 5 -1 0

Extracting elements
a(3) % third element, result: 5
a(3:5) % elements from 3 to 5, result: 5 -1 0
a(1:2:5) % elements from 1 to 5 w. increment 2, result: 1 5 0


Vector maths
b=[1,2,3,4,5]

a*2 % regular scalar multiplication
a.*b % element-by-element multiplication
a./b % element-by-element division
% '.' means element-by-element
b.^2 % square each element of b, result: [1,4,9,16,25]
2.^b % raise 2 to each of the powers given in b, result: result: [2,4,8,16,32]

No comments: