ENGN2219: Computing for Engineering Simulation

Sample Answers to Lab Test 1

Sample Question 1

Given the function
  y = xcos(x)
evaluate y for 30 evenly spaced values of x in the range -140 degrees to 120 degrees. Display this as a two column table, with the values of x being in the first column and y in the second.

Save this script in a file named evaluate1.m.

evaluate1.m

x=linspace(-140,120,30);
y = x.*cosd(x);
result=[x' y'];
disp(result);

Sample Question 2

Let A be a matrix with two rows. Let x be a vector corresponding to the first row and y a vector corresponding to the second row A. Write a function transform2(A,theta) that returns two vectors, xnew and ynew, given A and the angle theta in degrees, with the values of xnew and ynew calculated as follows:
   xnew = xsin(theta) + y2tan(theta)
   ynew = x3cos(theta) - ysin(theta)

Save this file as a script. Test this function by invoking it from matlab.

transform2.m

function [xnew ynew] = transform2(A,theta)

x=A(1,:);
y=A(2,:);
xnew = x.*sind(theta) - (y.^2).*tand(theta);
ynew = (x.^3).*cosd(theta) - y.*sind(theta);

Sample Question 3

A function f(n) is defined as follows:

Implement this as a recursive function recurse1(n). It should return the value of f(n), given n.

Save this file as a script. Test this function by invoking it from matlab.

recurse1.n

function ans = recurse1(n)

if (n == 0) || (n == 1)
  ans = 1;
else
  ans = recurse1(n-1) + recurse1(n-2);
end