Very Brief Matlab Tutorial
>> xv=(1:2:7)' % create a column vector of x coordinates
xv =
1
3
5
7
>> yv=[1 2 3 7]' % column vector of y coordinates
yv =
1
2
3
7
>> format compact % to eliminate blank lines in output
>> A=[xv.^0 xv.^1 xv.^2] % cool! raise xv to powers and form matrix!
A =
1 1 1
1 3 9
1 5 25
1 7 49
>> flops(0) % reset floating point operation (flop) counter
>> A\yv % find least squares solution to A*c=yv, where
% A is 4x3, c is 3x1, yv is 4x1,
% (in this case fitting quadratic
% function to the four points in xv and yv vectors)
ans =
1.5125 % coeffs of quadratic function
-0.5500
0.1875
>> flops % how many flops were used to solve?
ans =
200
>> plot(xv,yv) % plot a curve
>> size(A) % several ways to print the size of a matrix
ans =
4 3
>> sprintf('A matrix is %g by %g', size(A,1), size(A,2))
ans =
A matrix is 4 by 3
>> disp(sprintf('A matrix is %g by %g', size(A,1), size(A,2)))
A matrix is 4 by 3
>> [1 1e-8]
ans =
1.0000 0.0000 % note that 1e-8 is printed as 0
>> format short g
>> [ 1 1e-8]
ans =
1 1e-08 % but with "format short g", it's not
>> gausscost(10); % call a user-defined function
% below is an example of a function definition
% note: semicolons on the end of a statement suppress printing
function cost = gausscost(n)
% return cost of Matlab's Gaussian elimination routine on n x n system
A = rand(n,n); % create n x n random matrix
b = rand(n,1); % create n x 1 random vector
flops(0); % reset flop counter
A\b; % solve n x n system and discard answer
cost = flops; % return value is #flops
disp(sprintf('%gx%g costs %g', n, n, cost));
return;
15-859B, Introduction to Scientific Computing
Paul Heckbert
Sept. 2000