UTK - Math 171 - Alexiades
Enter very big and very small numbers in scientific notation:
e.g. 3.14e6 , 3.14e-6
Print very big and very small numbers with '%e' formating.
Guard against subtraction of nearly equal numbers,
multiplying by very small number
(or dividing by very large number).
Try to re-write the expression somehow.
The quadratic formula is subject to loss of significant digits
when 0 < 4ac << b2 (much less than)
A safe way to find roots of a quadratic:
x1 = ( −b−sign(b)√(b2−4ac) ) / 2a ,
x2 = c / ax1
Always evaluate polynomials in nested form:
saves operations and may reduce roundoff.
e.g. ax2 + bx + c = c + x*(b+a*x) ,
e.g. ax3 + bx2 + cx + d = d + x*(c+x*(b+a*x)) , etc
All variables inside a function are local to the function.
Only output variables will return to calling program.
Variables in a script (and workspace) are global,
can be passed to functions called by the script.
A = rand(m,n) : m×n matrix of random numbers drawn uniformly from (0 , 1)
If x is an array: [m, imin] = min(x) gives smallest
element m and the index imin where it occurs.
If x is an array: [M, imax] = max(x) gives largest
element M and the index imax where it occurs.
If A is a matrix: A(:) is 1D array of A by columns.
r3=A(3,:) is 3rd row of A, c3=A(:,3) is 3rd column of A.
If A is a matrix: [m, imin] = min( A(:) )
gives min element of A and its index in the array A(:).
Preallocate arrays (before entering loops):
a = zeros(1,N); b = zeros(M,1); A = zeros(M,N);
Calculation with arrays is faster than via loops on components,
especially in Matlab.
sum, min, max on a matrix A operate on each column of A.
Use A(:) = col array of columns of A.
Finding Sum, Min, Max of matrix of size M×N using nested loops:
M = input('enter M: ')
N = input('enter N: ')
A = 10*rand(M,N);
%----using array ops: on A(:), else they apply on each column
arraySum = sum( A(:) ); fprintf(' arraySum= %f \n', arraySum )
[arrayMin, iarrayMin] = min( A(:) )
fprintf(' arrayMin= %f at i: %d \n', arrayMin, iarrayMin )
[arrayMax, iarrayMax] = max( A(:) )
fprintf(' arrayMax= %f at i: %d \n', arrayMax, iarrayMax )
Sum = 0 ; Min = Inf ; Max = -Inf ;
for i = 1:M % for each row i
for j = 1:N % for each col j
aij = A(i,j); %save to avoid multiple lookups
Sum = Sum + aij;
if( aij <= Min )
Min = aij; iMin = i; jMin = j;
if( aij >= Max )
Max = aij; iMax = i; jMax = j;
fprintf(' Sum= %f \n', Sum)
fprintf(' Min= %f at i,j: %d %d \n', Min, iMin, jMin )
fprintf(' Max= %f at i,j: %d %d \n', Max, iMax, jMax )
important Matlab built-in functions:
input linspace sort plot fopen,fclose
fprintf fscanf fgetl feof