Octave Notes

Embed Size (px)

Citation preview

1. Octave Basic operations Arithmeticoperators: >> 5+6 ans = 11 >> 3-2 ans = 1 >> 5*8 ans = 40 >> 1/2 ans = 0.50000 >> 2^6 ans = 64 Logical operators: (0 meansFalse,1 or greatermeansTrue) >> 1 == 2 ans = 0 >> 1 ~=2 ans = 1 >> 1 && 0 ans = 0 >> >> 1 || 0 ans = 1 >> >> xor(1,0) ans = 1 Changingcursor: octave3.2.4.exe:11>PS1(>> ); Semicolonsuppressingoutput: >> a = 3 a = 3 >> a = 3; >> b = hi; >> c = (3>=1); >> c c = 1 >> a = pi; >> a a = 3.1416 Functionto displayoutput: >> disp(a); 3.1416 >> disp(sprint(2decimals:%0.2f,a)) 2 decimals:3.14 2. >> disp(sprint(6decimals:%0.6f,a)) 6 decimals:3.141593 >> formatlong >> a a = 3.14159265358979 >> formatshort >> a a = 3.1416 Matrix: >> A = [1 2 ; 3 4 ; 5 6] A = 1 2 3 4 5 6 Size of matrix: >> size(A) ans = 3 2 Vector: >> v = [1; 2; 3] v = 1 2 3 >> Range: >> v = 1:6 v = 1 2 3 4 5 6 >> v = 1:2.5:10 v = 1.0000 3.5000 6.0000 8.5000 Special Matrix functions: >> ones(2,3) ans = 1 1 1 1 1 1 >> c = 2 * ones(2,3) c = 2 2 2 2 2 2 >> w = ones(1,3) w = 1 1 1 >> w = zeros(1,3) 3. w = 0 0 0 Randomfunction: >> w = rand (1, 3) w = 0.91477 0.14359 0.84860 >> rand(3,3) ans = 0.58714 0.97976 0.72846 0.57976 0.91671 0.87487 0.55249 0.94451 0.90062 GaussianRandom: >> randn(1,3) Histogram: >> w = -6 + sqrt(10)*(randn(1,4)) w = -10.26499 -6.16161 -3.38088 -0.99144 >> w = -6 + sqrt(10) * (randn(1,100000) >>hist(w) Histogramwith50 bins >> hist(w,50) Identitymatrix: >> eye(4) ans = Diagonal Matrix 4. 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 >> >> eye(2,4) ans = Diagonal Matrix 1 0 0 0 0 1 0 0 >> helpcommand >> helpeye >> helphelp Moving data around >> A = [1 2; 3 4; 5 6] %a 3 by2 matrix A = 1 2 3 4 5 6 >> size(A) ans = 3 2 size(A) itselfreturns1*2 matrix >> sz = size(A) sz = 3 2 >> size(sz) ans = 1 2 Returns first dimensionofA (i.e.numberof rows) >> size (A,1) ans = 3 Returns seconddimensionofA (i.e.number of columns) >> size (A,2) ans = 3 >> v = [1 2 3 ] v = 1 2 3 Returns size of the longestdimension >> length(v) ans = 4 %( itis 1 by 4 matrix) >> length(A) %recall thatA is 3 by2 matrix ans = 3 5. Usuallylengthfunctionis appliedto vectors >> v = [1;2;3 ] v = 1 2 3 Current directoryor path: >> pwd ans = D:coursesSP-14MLHumayounex1ex1 >> cd 'D:courses' >> pwd ans = D:courses You can use otherLinux commandsas well,suchasls, dir(windowscommand if runningWindows) Loading Data files(usuallycomma separatedfieldsina record) >> loadfeaturesX.dat >> loadpriceY.dat Variablesin the current scope: >> who J_vals ans i m priceY theta0_vals y X data iterations predict1 t theta1_vals alpha featuresX j predict2 theta v For detailedviewof variables: >> whos Variablesinthe currentscope: Attr Name Size Bytes Class ==== ==== ==== ===== ===== J_vals 100x100 80000 double X 97x2 1552 double alpha 1x1 8 double ans 1x36 36 char featuresX 27x2 432 double . You can clear variablesby >> clearvariable_name Clear all variables >> clear You can viewdata: >> featuresX featuresX= 2104 3 1600 3 2400 3 6. 1416 2 3000 4 >> size (featuresX) ans = 47 2 >> size(priceY) ans = 47 1 Selectingdata: >> v = priceY(1:10) Save first10 elementsinv >> v = priceY(1:10) v = 3999 3299 3690 2320 5399 2999 3149 1989 2120 2425 Saving resultsin a file: >> save hello.matv; >> loadhello.mat It will load variable v >> v v = 3999 3299 3690 With>> save hello.matv, data is saved incompressedformat. You can also save it in ascii format: 7. >> save hello.txtv ascii >> A [1 2; 3 4 ; 5 6] A = 1 2 3 4 5 6 >> A(3,2) ans = 6 : means everythinginthat row/column Thirdrow and all columnsinthisrow >> A(3,:) ans = 5 6 First column >> A(:,1) ans = 1 3 5 Selectmore than one row: First and third row >> A([13], :) ans = 1 2 5 6 Assigningnewvalues to secondcolumn: >> A(:,2) = [10; 11; 13] A = 1 10 3 11 5 13 Appendanother column vector to right >> A = [A,[100; 101; 102]] A = 1 10 100 3 11 101 5 13 102 Put all elementsintoa single vector >> A(:) ans = 1 3 5 10 8. Making a matrix from othermatrices: >> C = [A B] >> A = [1 2; 3 4] A = 1 2 3 4 >> B = [11 22; 33 44] B = 11 22 33 44 >> C = [A B] C = 1 2 11 22 3 4 33 44 >> C = [A;B] C = 1 2 3 4 11 22 33 44 Computing on data Matrix multiplication: >> A * B ans = 77 110 165 242 Elementwise multiplication >> A .* B Elementwise squaring >> A .^2 >> A .^B Elementwise reciprocal >> 1./A Elementwise log >>log(A) Exponentiatione^element >>exp(A) >>abs(-A) >>A >>ones(3,1) ans = 9. 1 1 1 >> v+ ones(length(v),1) ans = 2 3 4 5 Easy way: >> v+1 Transpose >> v ans = 1 2 3 4 (v)= v >> (v) Max value: >>max (v) ans = 4 Value and its index >> [val,ind] = max(v) val = 4 ind= 4 >> A A = 1 2 3 4 >> A> find(A> find(A> A = magic(3) A = 8 1 6 10. 3 5 7 4 9 2 Sum column wise A = 1 2 3 4 5 6 7 8 9 >> sum(A) ans = 12 15 18 >> v=[1 2 4 5] v = 1 2 4 5 >> sum(v) ans = 12 Other useful matrix functions: >> ceil(A) >> floor(A) >> rand(3) >> max(A,B) max elementsfromcorrespondingrowscolumns >> max(A,[],2) %2for rowmax ans = 8 7 9 >> max(A,[],1) %1 forcolumnmax ans = 8 9 7 >> max(A) %columnmax,bydefault ans = 8 9 7 >> max(max(A)) ans = 9 >>A(:) ans = 8 3 4 1 5 9 6 7 2 >> max(A(:)) 11. ans = 9 >> sum(A,1) %columnwise ans = 15 15 15 >> sum(A,2) %rowwise ans = 15 15 15 Summingdiagonals: >> A = magic(5) A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 >> eye(5) ans = Diagonal Matrix 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 >> A.*eye(5) ans = 17 0 0 0 0 0 5 0 0 0 0 0 13 0 0 0 0 0 21 0 0 0 0 0 9 >> sum(sum(A.*eye(5))) ans = 65 >> flipud(eye(5)) ans = PermutationMatrix 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 Inverse of a matrix (calledpseudoinverse) >> pinv(A) 12. Plotting data Generate some data: >> t = [0: 0.01: 0.98] >> y1 = sin(2*pi*4*t); >> plot(t,y1); >> y2 = cos(2*pi*4*t); >> plot(t,y2); >> plot(t,y1); >> holdon >> plot(t,y2,'r'); >> xlabel(time) >> ylabel(value) >> legend(sin,cos) >> title(MyPlot) To close oldplots from memory: >> close >> figure(1);plot(t,y1); >> figure(2);plot(t, y2); To plot two figuresin two elementsside byside: 13. Dividesa plot in 1 by 2 grid >> subplot(1,2,1) % lastone is to accessthe firstelement >> plot(t,y1) % plotit infirstslot >> subplot(1,2,2) %lasttwo isto access the secondelement >> plot(t,y2) To change the axis scale: >> axis[0.51 -1 1] To clear a figure (the openedfigure): >> clf A neat trick to visualize the matrix: >> A = magic(5) A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 Plotsthe 5 by5 matrix ina 5 by 5 gridof colorswhere the differentcolorscorrespondtothe differentvaluesinthe matrix A. >> imagesc(A) See the legend ofthe colorsin the side of the picture. >> colorbar Three commands together: >> imagesc(A),colorbar,colormapgray; Visualize a biggerMatrix: >> imagesc(magic(15)),colorbar,colormapgray; 14. Control statements:for,while, if statements for loop: >> v=zeros(5,1) v = 0 0 0 0 0 >> for i=1:5, > v(i) = 2^i; > end; >> v v = 2 4 8 16 32 >> indices=1:5 indices= 1 2 3 4 5 >> for i=indices, > disp(i); > end; 1 2 3 4 5 while loop: >> i = 1; 15. >> while i disp(i); > i=i+1; > end; 1 2 3 4 5 >> i=1; >> while true, > v(i)=i; > i=i+1; > if i==6, > break; > end; > end; >> v v = 1 2 3 4 5 >> >> if v(1)==1, > disp('The value one'); > elseif v(2)==2, > disp('The value istwo'); > else > disp('The value is notone or two'); > end; The value one Creatinga function: Create sqrN.mfile inatexteditorandtype inthe following: functiony= sqrN(x) y = x^2 ; Nowsave the file andwithcd commandgo to the directorywhere youhave placedit.Now type: 16. >> sqrN(5) 25 Add a path to Octave search path: >> addpath(c:Users...ex1) Functionsreturning multiple values: function[y1,y2] = sqrAndCube(x) y1 = x^2; y2 = x^3; >> [y1,y2]=sqrAndCube(2) y1 = 4 y2 = 8 Vectorial implementation >> X = [1 1; 1 2; 1 3] X = 1 1 1 2 1 3 >> y=[1; 2; 3] y = 1 2 3 >> theta= [0;1] theta= 17. 0 1 >> j = costFunctionJ(X,y,theta) j = 0 Update theta: >> theta= [0;0] theta= 0 0 >> j = costFunctionJ(X,y,theta) j = 2.3333 >> (12 + 22 + 32)/6 = 2.3333 18. >> p r e d i c t i o n = theta'* x ;