1EGR 423 W’01Scilab Quick Reference• Constants:%i, %pi, %e: %eps: the smallest non-zero real number%t, %f: true and false (e.g., 2==2 gives %t)%inf:%nan: NaN, not-a-number• Entry of vectors:v = [1, 2, 3] // row vectorv = [1; 2; 3] // column vectorv = [v, 1]; // Adding to an existing vector• Indexing vectors:w = v(1:3); // Extract a sub-vectorv(1:3) = [0,0,0]; // Replace a sub-vector in-placev(5:$) // $ means the last indexv(5:length(v)) // same as v(5:$)v = v(:); // Force v to be a column vector• Entry of matrices:m = [1,2,3; 4,5,6; 7,8,9;] // row-at-a-timem = [[1;2;3], [4;5;6], [7;8;9]] // column-at-a-timem = [1,2,3; 4,5,6; 7,8,9;].’ // rowwise, then transpose• Indexing matrices:M = A(1:4, 2:3); // Extract a submatrixM = A(:, 3:5); // Extract whole rowsM = A(1, :); // Extract whole columnsx = A(3,5); // Indexing single elementsA(3,:) = [0,0,0]; // Replace a row in-placeA(:,4) = [1;1;1]; // Replace a column in-place• Operations on complex numbers:z = 2+3*%i; // entry of complex constantsconj(z); // complex conjugatereal(z); // real partimag(z); // imaginary partabs(z); // magnitude atan(imag(z),real(z)); // phase HINT: deff(‘p=phase(z)’, ‘p=atan(imag(z),real(z))’)(if you are offended by the lack of a built-in phase function)[r,p] = polar(z);// compute j π e,,∞zz∠rz=p, z∠=2• Operations on matrices:C = A*B; // Matrix multiplicationC = A .* B;// Elementwise multiplication (Kronecker product)C = A^2; // Same as A*AC = A.^2; // Elementwise power operationC = A+B-C; // Matrix addition, subtractionx = A/b; // Solution to x*b=A, NOT MATRIX “DIVISION”C = A ./ B; // Elementwise division1C = 3*A/2; // Scalar distributes over arrayC = A.’; // Matrix transposeC = A’; // Matrix Hermitian (conjugate transpose)C = zeros(3,4);// Matrix of all 0’sC = ones(2,2); // Matrix of all 1’sC = eye(4,4); // Identity matrixd = diag(A); // Extract the diagonal of matrix AA = diag(d); // Construct diagonal matrix from vector dd = det(A); // DeterminantAi = inv(A); // Matrix inverse[row,col] = size(A);// Determine array dimensions• Useful functions:abs(x); // Absolute value (or complex magnitude)exp(x); // log(x), log10(x)// Natural logarithm, base-10 logarithmint(x); // Truncate real to integermin(v); // Minimum of a vector or matrixmax(v); // Maximum of a vector or matrixmedian(v); // Median of a vector or matrixmean(v); // Average value of a vector or matrixfind(v); // Return INDICES where v is true2sin, cos, tan, asin, acos, atan// Trigonometricsrand(3,4); // Create random arraysum(v); // Sum up all elements in vprod(v); // Multiply together all elements in vcumsum(v); // Cumulative sumcumprod(v); // Cumulative productlinspace(1,10,4); // Create a linear rangelogspace(0,4,4); // Create a logarithmic rangenorm(M); // Matrix normclear v // Remove variables from workspace1. A BIG gotcha: the expression “1./A” and “1 ./ A” are different, because of the way the dot ‘.’ is either associated with the 1 or the / operator. The first expression “1./A” is really (1.0)/A and does NOT imple-ment the element-wise reciprocal of each matrix entry. That’s what the second expression does, “1 ./ A”.2. The idiom to find, for example, where in a vector a certain value exists is “find(v == 3)”. Consider, for example, the idiom for finding a local maximum: “find((v(2:$-1) > v(1:$-2)) & (v(2:$-1) > v(3:$)))+1”ex3save(‘c:\backup.dat’); // Save workspace to fileload(‘c:\backup.dat’); // Load workspace from filediary(‘c:\diary.dat’); // Start a diarydiary(0); // Stop a diary• Selected operators:&, |, ~ // logical AND, OR, NOT (not bitwise and,or,not)**, ^ // exponentiation (synonyms)= // assignment (e.g., “v=3”)== // logical equality (e.g., “tf = (v==3)”)~= // logical non-equality (e.g., “if v ~= 3”)<, >, <=, >= // logical inequality tests• Polynomials:z = poly(0,’z’); // Create the polynomial P(z)=z ...p = z^2 + 3*z; // ... then use P(z) to form p = poly([0,3,1], ‘z’, ‘coeff’);// Alternate wayp = poly([0,-3], ‘z’, ‘roots’); // Polynomial from rootsroots(p); // Find polynomial rootspolfact(p); // Factor polynomialhorner(p,3); // Evaluate polynomial at a numberhorner(p,z^2+1); // Polynomial substitutionp*q, p/q, p+q // Polynomial operationsnumer(p); // Numerator of polynomial fractiondenom(p); // Denominator of polynomial fraction• Control Flow:if i > 2,stuff();endif i ~= 3,stuff();elseother();endwhile i < 10,disp(i);endfor i=1:10,disp(i);endz23z+4for str = [‘abc’, ‘def’],printf(“String: %s”, str);endselect value,case 0,printf(“Ooops...value is 0!”);case 1,printf(“It’s 1”);elsebreak;end• Functions:function noargs() // No return value, no parametersfunction onearg(x) // No return value, one parameterfunction twoargs(x,y) // No return value, two parametersfunction x = stuff(x,y) // One return valuefunction [x,y]=stuff(a,b)// Two return valuesgetf(‘c:\myfunc.sci’); // Load function into workspacedeff(‘tryit’, ‘exec(‘‘c:\tryit.sce’’)’);// On-the-fly function definitionfunction [a,b,c]=checkargs(x,y,z)// Shows how to check for the number of parameters// actually passed and how many return values were// asked for.[lhs,rhs] = argn(0);printf(“You specified %d parameters”, rhs);printf(“You asked for %d return values”, lhs);if rhs < 3,z = 0; // default valueendif rhs < 2,y = 10; // default valueend• Plotting:plot(v); // Simplest way to plot a vectorplot(xaxis,y); // Plot y against axis in a vectorplot(x,y,’t’,’x(t)’,’Title’);// Specify captions and titleplot2d(...); // Control over plot styles, axes, legendplot2d1(...); // Also allows logarithmic axesplot2d2(...); // Piecewise constant (stairstep) curves5plot2d3(...); // Isolated vertical barsplot2d4(...); // Arrowsxbasc(); // Clear plot windowxdel(); // Close plot windowerrbar(...); // Add error barslocate(...); // Pick values off a graph with the mousexclick(); // Wait for mouse button press in windowx_dialog(‘Message’, ‘Press OK’);// Create dialog window• Linear Systems:H = syslin(‘d’, z^2+1, 1-z);// Create linear system with// H(z) = N(z)/D(z)// and z=poly(0,’z’)H(‘num’) or numer(H) // Extract numeratorH(‘den’) or denom(H) // Extract denominatorH*G // Linear systems in seriesH+G // Linear systems in parallelH /. G // Negative feedback configuration[f,r]=repfreq(H); // Frequency responsepfss(H); // Partial fraction decompositiony=rtitr(numer(H), denom(H), u);// Time
View Full Document