# 2015F001/Homework5

### From CDS 130

# 1. What output results from running the following Matlab code?

a = 1 + 2 * (3 \( 4*(5 - 6/3))); a = a * a b = -1*a/9 c = b^2 - 25.0 d = a - b + c*c display (a)

a =81

b =-9

c =56

d =3226

a =81

# 2. Matlab Assignment

Create a variable called m and assign to it the value 1.0. Then create the following variables and assign to them the following values:

n __m squared minus 3__

p __m cubed minus the cosine of m__

q __m divided by the cube of the quantity m squared plus 1__

r __negative two plus the square root of m__

s __the cosine of the following quantity: n divided by the quantity p plus r__

Matlab code:

m= 1.0; n= (m^2)-3; p=(m^3)-cos(m); q= m/((m^2)+1)^3; r= -2+(m^2); s= cos(n/(p+r))

# 3. Without running Matlab, what output results from running the following Matlab code?

%% A matlab code to test arithmetic functions. a = 0.0; b = 4.0; a = a + 2; b = a + 2; a = sqrt(a) + a ; b = a + b\2; b = ceil (b); a = round (a); c = mod (a, round(b)); a b c

Ans:

a= 4 b= 5 c= 1

# 4. Use Matlab to evaluate the following expressions.

- floor( − 7.6)
- ceil(3.4)
- round(5.5)

Ans=

- 137.7573
- 3.9369
- 1.7185e-07
- 1
- 2
- -8
- 4
- 6

# 5. Variables are programmer-designated names that can represent a specific value of data. Like other programming languages, MATLAB also has a set of rules for naming variables. If the rules are violated, the variables can not be treated as valid variables, causing programming errors.

Create four "invalid" variable names with different reasons, and state the reason why the variable names can not be used in MATLAB.

2eee2e2 it starts with a number e four it can't have a space King-dedede it can't have a hyphen BBB*F it can't have a multiplication symbol

# 6. Anonymous function in Matlab

An anonymous function defined in matlab is a function that is not stored in a program file, but associated with a variable. Provide a matlab script in which a mathematical function f(x,y) is defined as

f(x,y) = cos(x^{3}) + sin(y^{3}) + e^{x-y}

Calculate the values of f(0.3,0.2), f(3,2), f(π, π / 2) using the defined anonymous function in Matlab.

# 7. Suppose that you have defined the function foo as follows

function y = foo(x) z = x / 2; y = x - z^2; end

what are the values from the following calls?

>> foo(2)= 1

>> foo(foo(2))= 0.7500

# 8. Write a Matlab function (m file) to evaluate the function logfunc(x, y) = log10(x^{2}) - log10(y^{2})

(1) show your m-file for this function;

f= @(x,y) log10(x^2)-log10(y^2)

(2) calculate logfunc(3, 2) and logfunc(-5, -3)

0.3522 and 0.4437