UNB/ CS/ David Bremner/ teaching/ cs2613/ labs/ Lab 20

Before the lab

Background


Working with grids

Time
15 minutes
Activity
Demo

Defining and testing a function

Time
20 minutes
Activity
individual

In the rest of this lab we want to use Octave to explore the function

    δ(β, a, b) = βa·b - (β-1)b·b

Here β is a scalar (a number) and a and b are vectors of length 2. We curious what the zeros of this function are for fixed β and a. One approach is to try plotting that surface as a function of b. We'll start by defining and testing a function for beta

    ## compute βa·b - (β-1)b·b
    ## a, b are assumed to be column vectors, beta is a scalar
    function ret = delta(beta, a, b)

    endfunction
%% delta(0,a,b) = |b|²
%!test
%!
%!
%!

%% delta(1,a,b) = a.b
%!test
%!
%!
%!

%% delta(2,a,b) = 2a.b - |b|²
%!test
%!
%!
%!

Making 3D plots

Time
20 minutes
Activity
Small Groups
a = [4;4];
beta = 7.5;

%% Generating vectors
range = [-4:0.1:8];

% Compute cartesian product (grid)
[X,Y] = meshgrid(range,range);







surf(X,Y,Z);


Using arrayfun

Time
25 minutes
Activity
individual
a = [4;4];
beta = 7.5;
range = [-4:0.1:8];
[X Y] = meshgrid(range,range);

f=
Z=arrayfun(f,X,Y);

surf(X,Y,Z);

Fully vectorizing

Time
25 minutes
Activity
individual

If we expand out a single call to delta in our for loop, we get

Z(i,j) = beta * (a(1)*X(i,j) + a(2)*Y(i,j)) - (beta-1) * (X(i,j)^2 + Y(i,j)^2)
function ret = arraydelta(beta,a,X,Y)

  ret =
endfunction

%!test
%! a = rand(2,1)
%! X = [2,2;2,2]
%! Y = [-1,-1;-1,-1]
%! assert (arraydelta(0, a, X,Y),[5,5; 5,5],eps)
%!test
%! a = rand(2,1);
%! beta = rand*6;
%! X = rand(10,10);
%! Y = rand(10,10);
%! assert (arraydelta(beta, a, X,Y), arrayfun(                            , X, Y), eps)
a = [4;4];
beta = 7.5;

range = [-4:0.1:8];
[X Y] = meshgrid(range,range);

Z=arraydelta(beta,a,X,Y);

surf(X,Y,Z);