The functions we wrote in class are provided below. Each lists the filename, a description of what we're illustrating, and then the file contents. You can cut & paste as needed.

square.m : a super-simple example of a function that takes one argument and returns one value

function s = square(x);  % declare a function named square 
% square takes an argument x and returns its square, s=x*x

  s = x*x;
  
end

pow.m : an example of a function that takes two arguments

function y = pow(x,n) % this function takes two arguments
% pow(x,n): return x to the n

  y = x^n; % semicolon to suppress printing
  
end

square_cube.m : an example of a function with two return values

function [s,c] = square_cube(x); % example of multiple return values
% return the square and the cube of x

  s = x*x;
  c = s*x;
  
end

isOdd.m : an example of an if-else statement

function r = isOdd(n)
% return 1 if n is odd, 0 if n is even

  if 2*floor(n/2) ~= n  % this will test if n is not even
    r = 0; 
  else
    r = 1;  
  end

isTwo.m : a simpler example of an if-else statement

function r = isTwo(n);
% return 1 (true)  if n is two, 
%        0 (false) if n is not two

  % simple example of an if statment
  if n == 2
    r = 1; % true, n is two
  else
    r = 0; % false, n is not two
  end
  
end

printtoten.m : a simple example of a for-loop, with no arguments and no return value

function printtoten(); 
% print the numbers from 1 to 10

  % example for loop
  for n=1:10
    n 
  end
  
end

sumtoten.m : a more meaningful example of a for-loop

function s = sumtoten();
% return the sum of 1 through 10

  s = 0; % set s to zero

  for n=1:10
    s = s+n;   % add each number from 1 to 10 to s
  end

end

matvecmult.m : a home-grown matrix-vector multiply function

function y = matvecmult(A,x);
% return y = A*x;

  [m,n] = size(A);  % get size of matrix
  
  y = zeros(m,1);

  % Compute y(i) = sum A_ij x_j
  
  % "nested loops"
  for i=1:m
    for j=1:n
      y(i) = y(i) + A(i,j)*x(j);
    end
  end
  
end