1.Basic operations
%generate a matrix a = [1,2,3;4,5,6] a = 1 2 3 4 5 6 a = [1,2,3;4,5,6]; % The end ';' will inhibit the output of assignment operation %generate a vaector a = [1 2 3]; a = [1:3]; %specific matrix or vectors ones(3,1) zeros(0,1) a = ones(3,1); a(1) = 0; a %change or add one row or one column of a matrix octave:33> a = [1 2 3]; octave:34> a = [a;a] a = 1 2 3 1 2 3 octave:35> a = [a a] a = 1 2 3 1 2 3 1 2 3 1 2 3 octave:36> a = [a a ones(2,1)] a = 1 2 3 1 2 3 1 2 3 1 2 3 1 1 2 3 1 2 3 1 2 3 1 2 3 1 octave:37> a = [a ; ones(1,size(a,2))] a = 1 2 3 1 2 3 1 2 3 1 2 3 1 1 2 3 1 2 3 1 2 3 1 2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 octave:38> a[1,] parse error: syntax error >>> a[1,] ^ octave:38> a[1,:] = zeros(1,size(a,2)) parse error: syntax error >>> a[1,:] = zeros(1,size(a,2)) ^ octave:38> a(1,:) = zeros(1,size(a,2)) a = 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 1 2 3 1 2 3 1 2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 octave:39> a(:,1) = ones(size(a,1),1) a = 1 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 1 2 3 1 2 3 1 2 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2.Get the maximum value from a matrix
octave:12> a = [1,2,3;4,5,6;7,8,9] a = 1 2 3 4 5 6 7 8 9 octave:13> max(a) #default by columns ans = 7 8 9 octave:14> [value, index] = max(a) #return the largest value of each column and their rows value = 7 8 9 index = 3 3 3
3.Get unique values of a vector
octave:23> a = [1 2 3 4 5 1 2 3 4 5 1 2 3 4 5] a = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 octave:24> unique(a) ans = 1 2 3 4 5
4.Get the number of rows and columns of a mtrix
octave:27> a = [1 2 3 4 5; 1 2 3 4 5 ;1 2 3 4 5] a = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 octave:28> size(a) ans = 3 5 octave:29> size(a,1) % number of rows ans = 3 octave:30> size(a,2) % number of columns ans = 5 octave:31> a = [1 2 3 4 5 1 2 3 4 5 1 2 3 4 5] a = 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 octave:32> size(a) ans = 1 15
5.Get the position of one special value or change one special value to 0
octave:48> a = [ones(5,1);zeros(5,1)]; octave:49> pos_a = find(a==1) pos_a = 1 2 3 4 5 octave:50> a(pos_a,:) ans = 1 1 1 1 1 octave:51> zero_a = find(a==0) zero_a = 6 7 8 9 10 octave:52> a(zero_a,:) ans = 0 0 0 0 0 %------------------------------------------ octave:53> a = [1,2,3,4,5,1,2,3,4,5] a = 1 2 3 4 5 1 2 3 4 5 octave:54> a == 1 ans = 1 0 0 0 0 1 0 0 0 0 octave:55> a == 5 ans = 0 0 0 0 1 0 0 0 0 1
6.repmat — repeat a given matrix by given number of times in row and column
octave:24> a = ones(3,4) a = 1 1 1 1 1 1 1 1 1 1 1 1 octave:25> repmat(a,1,2) ans = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 octave:26> repmat(a,2,2) ans = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
7.
- 9.