You are on page 1of 16

Basic Syntax and Command Line

Exercises
1.

Create a vector of the even whole

3. Let x = [3 2 6 8]' and y = [4 1 3


5]'
>> x = [3 2 6 8]'

numbers between 31 and 75.


>> x = 32:2:75

x =

x =

Columns 1 through 13
32
44

34
46

36

48

38
50

40
52

42
54 56

8
>> y = [4 1 3 5]'

Columns 14 through 22

y =

4
1

58
70

60
72

62

64

66

68

74

2. Let x = [2 5 1 6].

a.

a.

to y

Add 16 to each element

>> x+16
ans =

Add the sum of the elements in x

>> y+sum(x)
18

21

17

22

ans =

23
20

b.

Add 3 to just the odd-index

22

elements

24

>> x(1:2:end) + 3
ans =

b.

Raise each element of x to the

power specified by the corresponding


element in y.

c. Compute the square root of each


element

>>x.^y
ans =

81

>> sqrt(x)

ans = 1.4142

2.2361

1.0000

216

2.4495

32768

d.
Compute the square of
each element

c. Divide each element of y by the


corresponding element in x.

>> x.*x
ans =

25

36
>> y/x

ans =
0

0.5000
0

0.1250

c. 10 / 2 \ 5 - 3 + 2 * 4
>> 10 / 2 \ 5 - 3 + 2 * 4
ans =
6
d. 3 ^ 2 / 4

0.3750
0

0.6250
d. Multiply each element in x by the
corresponding element in y, calling
the result "z".

2.2500

e. 3 ^ 2 ^ 2
>> 3 ^ 2 ^ 2
ans =

81

f. 2 + round(6 / 9 + 3 * 2) / 2 3
>> 2 + round(6 / 9 + 3 * 2) / 2 - 3
ans =
2.5000

>> z=x.*y
z =

>> 3 ^ 2 / 4
ans =

12

g. 2 + floor(6 / 9 + 3 * 2) / 2 3

>> 2 + floor(6 / 9 + 3 * 2) / 2 - 3
ans =
2

18
40

h. 2 + ceil(6 / 9 + 3 * 2) / 2 3
e. Add up the elements in z and assign
the result to a variable called "w".

5.

>> w = sum (z)


w =

>> 2 + ceil(6 / 9 + 3 * 2) / 2 - 3
ans =
2.5000

72

f. Compute x'*y - w and interpret the


result

Create a vector x with the

elements ...
a. 2, 4, 6, 8, ...
>> a = 2:2:20
a =

>> x'*y - w
ans =

Columns 1 through 10
0

2
14

4. Evaluate the following MATLAB


expressions by hand and use MATLAB to
check the answers
a. 2 / 2 * 3

18

10

12

20

b. 10, 8, 6, 4, 2, 0, -2, -4
>> b = 10:-2:-4

>> 2 / 2 * 3
ans =

16

b. 6 - 2 / 5 + 7 ^ 2 1
>> 6 - 2 / 5 + 7 ^ 2 - 1
ans =
53.6000

b =
0

-2

10

-4

c. 1, 1/2, 1/3, 1/4, 1/5, ...


>> x = 1:5, y = 1./x , rats(y)

x =

y =

1.0000

0.2500

0.5000

a. ln(2 + t + t2)

0.3333

0.2000

>> a = log(2 + t + t.^2)


a =

ans =

1/2

1/3

1/4

1.3863

1.8181

1.9516

1.5347

1.6790

2.0794

1/5
b. et(1 + cos(3t))

d. 0, 1/2, 2/3, 3/4, 4/5, ...

>> b = exp(t).*(1 + cos(3*t))


b =

>> x = 0:4, y = 1:5, z = x./y ,

5.3864

rats(z)
x =

y =

z =
0.7500

0.5000

0.0272

0.6667

9.8893

c =
1/2

3/4

14.4838

>> c = cos(t).^2 + sin(t).^2


1.0000

1.0000
0

2.0671

c. cos2(t) + sin2(t)

0.8000

ans =

0.3428

1.0000

1.0000

1.0000

1.0000

2/3

4/5

d. tan-1(1)

6. Create a vector x with the


elements,

>> d = atan(t)
d =
1.0122

0.7854

xn = (-1)n+1/(2n-1)

1.0637

Add up the elements of the version of


this vector that has 100 elements.

e. cot(t)

>> n = 1:100;

>> e = cot(t)

x = ( (-1).^(n+1) ) ./ (2*n 1);

0.8761

e =
0.1725

1.1071

0.6421
-0.0292

0.9505

0.3888
-0.2333

-0.4577

y = sum(x)
f. sec2(t) + cot(t) 1
y =

0.7829

>> f = sec(t).^2 + cot(t) - 1

8. Given a vector, t, of length n,


write down the MATLAB expressions that
will correctly compute the following:

t =
1.8000

1.2000
2.0000

1.0e+003 *
0.0031
0.0070
0.0338
1.1718
0.0181
0.0043
9. Plot the functions x, x3, ex and ex
over the interval 0 < x < 4.

>> t = 1:0.2:2
1.0000

f =

1.4000

1.6000

a. on rectangular paper

c. on log-log paper
Be sure to use an appropriate mesh of
x values to get a smooth set of
curves.

b. on semilog paper (logarithm on


the y-axis)

term = 1 + exp(-0.0313*(t 1913.25));


P = 197273000./term;
plot(t,P)
xlabel('year'),
ylabel('population')
P2020 = 197273000/(1 + exp(0.0313*(2020 - 1913.25)))
P2020 =

1.9053e+008

10. Make a good plot of the function


f(x) = sin(1/x)
for 0.01 < x < 0.1. How did you
create x so that the plot looked good?
>>
>>
>>
>>
>>
>>

x=linspace(0.01,0.1,30);
y=sin(1./x);
plot(x,y)
hold on
title('Plot of f(x)= sin(1/x)')
hold off

12. Plot the expression

P(t) = 197,273,000/(1 + e-0.0313(t 1913.25)


)
where t is the date, in years AD,
using t = 1790 to 2000. What
population is predicted in the year
2020?
>> t = 1790:2000;

Array Exercises
1.
Given x = [3 1 5 7 9 2 6],
explain what the following commands
"mean" by
by summarizing the net result of
the command.

a. x(3)
>> x(3)
ans =

f. x([1 6 2 1 1])

>> x([1 6 2 1 1])

ans = 3

The value in the column 3

1 to column 7.

33

This command simply gives the

2. Given the array A = [2 4 1; 6 7 2;


3 5 9], provide the commands needed to

ans = 3

6
This command gives the all the
values in the array from column
1 to end.

a. assign the first row of A to a


vector called x1
>> x1 = A(1,:)
x1 =

b. assign the last 2 rows of A to an


array called y

d. x(1:end-1)

>> y = A(end-1:end,:)

>> x(1:end-1)
ans =

2
-

ans =

sum of all values in the array.

c. x(1:end)
>> x(1:end)

g. sum(x)
>> sum(x)

This command gives all the


values in the array from column

and 1 respectively.

ans = 3

the array of columns 1, 6, 2, 1

>> x(1:7)

This command gives the values in

b. x(1:7)

This gives all the values in the


array from column 1 to column 6
since 1 is subtracted from the
end.

y =

6
7
2
3
5
9
c. compute the sum over the columns of
A
>> sum(A)
ans =

11

16

12

d. compute the sum over the rows of A

e. x(6:-2:1)

>> sum(A')'
>> x(6:-2:1)
ans =
-

ans =
2

This command gives the values in


the array starting from column 6
up to column 1 with intervals of
2 columns.

7
15
17
e. compute the standard error of the
mean of each column of A (NB. the
standard error of the mean is defined
as the standard deviation divided by

the square root of the number of


elements used to compute the mean.)

>> [x ; y]
ans =

>> N = size(A,1)

N = 3

g. A - 3
>> A - 3

>> e = std(A)/sqrt(N)

ans =

e =

0
2

-2

1.2019

0.8819

-1

3
4

2.5166

3. Given the arrays x = [1 4 8], y =


[2 1 5] and A = [3 1 6; 5 2 7],
determine which of the ff. statements
will correctly execute and provide the
result. If the command will not
correctly execute, state why it will
not. Using the command whos may be
helpful here.

4. Given the array A = [2 7 9 7 ; 3 1


5 6 ; 8 1 2 5], explain the results of
the following commands:
>> A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5]
A =

a. x + y

ans = 2

>> x+y
ans =

13

b. x + A

a. A'
>> A'
7

Error using plus in the matrix, the


dimensions of the matrix x and A
should be the same.
c. x' + y
Error using plus in the matrix, the
dimensions of the matrix x and y
should be the same.

This command means the transpose


of matrix A, the rows and columns are
interchanged in this function.
b. A(:,[1 4])
>> A(:,[1 4])

d. A - [x' y']
Error using minus in the matrix,
the dimensions of matrix A and the
matrix of the product of x and y
should be the same.
e. [x ; y']
Error using vertcat, CAT arguments
dimensions are not consistent.
f. [x ; y]

ans =
2

The command gives a matrix that


includes only the numbers in the
columns and 4.
c. A([2 3],[3 1])
>> A([2 3],[3 1])

This command returns A with its


ans = 5

rows flipped in the up-down direction

(that is, about a horizontal axis)

Returns the values located at

g. fliplr(A)

row 2, column 3 and row 3, column 1.


>> fliplr(A)
d. reshape(A,2,6)

ans =

>> reshape(A,2,6)

ans = 2

6
This command returns A with its

columns

Reshape the matrix A into a 2 by 6

direction (that is, about a vertical

matrix

axis)

e. A(:)

h. [A(end,:)]

>> A(:)

flipped

in

the

left-right

>> [A(end,:)]

ans = 2
3

ans =

7
1

This command gives the values on


rd

the 3

row of matrix A.

9
5

i. A(1:3,:)
>> A(1:3,:)

ans =

5
Gives

all

the

elements

regarded as a single column.

of

A,

This

command

gives

all

the

values on matrix A that is on columns


1 to column 3.

f. flipud(A)
>> flipud(A)
ans = 8

j. [A ; A(1:2,:)]
>> [A ; A(1:2,:)]
ans =
2

a. assign the even-numbered columns of


A to an array called B
>> B = A(:,2:2:end)
B =

k. sum(A)

>> sum(A)
ans =
-

13

16

b. assign the odd-numbered rows to an


array called C

18

Gives the sum of the matrix

>> C = A(1:2:end,:)
C =
2
8

l. sum(A')
>> sum(A')
ans = 25
-

15

16

7
1

9
2

c. convert A into a 4-by-3 array


>> x = A'
x =
2
3
8
7
1
1
9
5
2
7
6
5

This command gives the sum of


the transpose of matrix A.

m. sum(A,2)
>> sum(A,2)

d. compute the reciprocal of each


element of A

ans = 25
15

>> rats(1./A)

16
This command returns the sum of matrix
A along the 2 dimension.
o. [ [ A ; sum(A) ] [ sum(A,2) ;

ans =
1/2
1/3
1/8

1/7
1
1

1/9
1/5
1/2

e. compute the square-root of each


element of A

sum(A(:)) ] ]
>> [ [ A ; sum(A) ] [ sum(A,2) ;
sum(A(:)) ] ]

>> sqrt(A)

ans =
2

25

ans =

15

2.6458

16

13

16

18

56

1.4142

2.6458

3.0000

1.7321

1.0000

2.2361

2.4495
2.8284

1.0000

1.4142

5. Given the array A from problem 4,


above, provide the command that will

2.2361

>>

6. Give the following commands to

A = [2 7 9 7 ; 3 1 5 6 ; 8 1 2 5]
A =

7
5

create an array called F:


5

>> randn('seed',123456789)
>> F = randn(5,10);
>> N=size(F,1)

1/7
1/6
1/5

d. If Pr(|t| > 2.132 ) = 0.1 with 4


degrees of freedom, are any of
the mean values
in the vector avg statistically
different from 0?

a. Compute the mean of each column


and assign the results to the
elements of a vector called avg.

None were different at 90% LOC

>> avg = mean(F)

(all < 2.132).

avg =
Columns 1 through 8
1.0265

-0.0674

-0.3151
-0.6386

-0.2153

-0.1415

0.3403

Relational and Logical Operations

-0.3431

1. Given that x = [1 5 2 8 9 0 1] and


y = [5 2 2 6 0 0 2], execute and
explain the results of the following
commands:

Columns 9 through 10
0.1726

0.3760

b. Compute the standard deviation of


each column and assign the
results to the elements of a
vector called s.

a. x > y
ans =0
0

0
-

This command evaluates whether

>> s = std(F)

the values in the array x is

s =

greater than array y and gives


1(true) and 0(false) as an

Columns 1 through 8
1.2131
0.7748

0.7533
0.9208

0.3313
1.1053

answer.
0.5499
1.0867

b. y < x

Columns 9 through 10
0.6738

ans =0
0

0.9204

0
-

c. Compute the vector of t-scores


that test the hypothesis that the
mean of each column is no
different from zero.

This command evaluates whether


the values in the array y is
less than array x and gives
1(true) and 0(false) as an

>> tscore = (avg - 0)./(s/sqrt(N))

answer.

tscore =
Columns 1 through 8
1.8922
-0.1999
-1.4533
-0.5754
-0.9093
0.8263
-1.2918
-0.7060

c. x == y
ans = 0
0

1
-

This command compares the values

Columns 9 through 10

in the array x and array y and

0.5729

gives 1(true) if they are equal

0.9134

and 0(false) otherwise.

d. x <= y

ans = 1
0

1
-

Performs a logical AND of x and

NOT y and returns an array

containing elements set to

This command evaluates whether

either logical 1 (true) or

the values in the array x is

logical 0(false).

less than or equal to array y


and gives 1(true) and 0(false)

i. (x > y) | (y < x)

as an answer.

ans =
1

e. y >= x

ans = 1
0

1
-

0
or (y<x) is

true, otherwise it will returns

This command evaluates whether

0(false).
-

greater than or equal to array x

j. (x > y) & (y < x)

and gives 1(true) and 0(false)


as an answer.

ans = 1

ans =
1

f. x | y

either one of (x>y)

It returns 1(true) whenever

the values in the array y is

2. Given x = 1:10 and y = [3 1 5 6 8 2


9 4 7 0], execute and interpret the
results of the following commands:

performs a logical OR of all

a. (x > 3) & (x < 8)

input arrays A, B, etc., and

ans = 0

returns an array containing

elements set to either logical 1


(true) or logical 0 (false)

Gives 1(true) if it satisfies


that x is greater than 3 and x is less

g. x & y

than 8 otherwise it returns 0(false).

ans = 1
0

0
-

b. x(x > 5)

Performs a logical AND of x and

ans = 6

10

y and returns an array


containing elements set to

Gives the numbers of x that is

either logical 1 (true) or

greater than 5.

logical 0 (false).
c. y(x <= 4)
h. x & (~y)
ans =
1

ans =
0

0
d. x( (x < 2) | (x >= 8) )
ans =

10

e. y( (x < 2) | (x >= 8) )
ans = 3
4
7

e. set the values in x that are less


than the mean to zero

f. x(y < 0
ans = Empty matrix: 1-by-0
3. You can see the
differences by
executing the following commands that
attempt to extract the elements
of y
that correspond to either the odd (a.)
or even (b.) elements of x:
a. y(rem(x,2)) vs.
y(logical(rem(x,2)))
>> y(rem(x,2))
??? Subscript indices must either be
real positive integers or logicals.
>> y(logical(rem(x,2)))

f. set the values in x that are above


the mean to their difference from the
mean.
x = [3 15 9 12 -1 0 -12 9 6 1]
a = x, idxa = x > 0,

b. y(~rem(x,2)) vs.
y(~logical(rem(x,2)))
>> y(~rem(x,2))

a(idxa) = 0

b = x, idxb = ~rem(x,3), b(idxb) = 3


c = x, idxc = ~rem(x,2), c(idxc) =
5*c(idxc)
5. Create the vector x = randperm(35)
and then evaluate the following
function using only logical indexing:
y(x) = 2
= x - 4
= 36 - x

ans =
3

d.extract the values of x that are


greater than 10 into a vector called
y

if x < 6
if 6 <= x < 20
if 20 <= x <= 35

You can check your answer by


plotting y vs. x with symbols. The
curve should be a triangular shape,
always above zero and with a maximum
of 16. It might also be useful to
try setting x to 1:35.

ans =
6

>> x = 1:35;

y = zeros(size(x));
>> y(~logical(rem(x,2)))

idx1 = x < 6;

ans =

idx2 = (x >= 6) & (x < 20);


6

idx3 = (x >= 20) & (x <= 35);

4. Given x = [3 15 9 12 -1 0 -12 9 6

y(idx1) = 2;

1], provide the command(s) that will

y(idx2) = x(idx2) - 4;
y(idx3) = 36 - x(idx3);

a. set the values of x that are


positive to zero.
b. set values that are multiples of 3
to 3 (rem will help here)
c.multiply the values of x that are
even by 5

disp([x(:) idx1(:) idx2(:)


idx3(:) y(:)])
plot(x,y,'o')

4.

a.
b.
c.
d.

if 0 < x < 10
y = 4*x
elseif 10 < x < 40
y = 10*x
else
y = 500
end
x
x
x
x

=
=
=
=

-1
5
30
100

y
y
y
y

= 500
= 20
= 300
= 500

Loop Constructs Exercises

Control of Flow: if-Blocks


1.

if n > 1
m = n+1
else
m = n - 1
end

a. n = 7
m = 8
b. n = 0
m = -1
c. n = -10 m = -11
2.

if z < 5
w = 2*z
elseif z < 10
w = 9 - z
elseif z < 100
w = sqrt(z)
else
w = z
end
a.
b.
c.
d.
3.

z
z
z
z

=
=
=
=

1
9
60
200

w
w
w
w

=
=
=
=

2
0
7.7460
200

if T < 30
h = 2*T + 1
elseif T < 10
h = T - 2
else
h = 0
end

a. T = 50
b. T = 15
c. T = 0

h = 0
h = 31
h = 1

1. Given the vector x = [1 8 3 9 0 1],


create a short set of commands that
will
a. Add up the values of the elements
total = 0;
for j = 1:length(x)
total = total + x(j);
end
b. Computes the running sum (for
element j, the running sum is the sum
of the elements from 1 to j,
inclusive. Check with cumsum.)
runningTotal = zeros(size(x));
runningTotal(1) = x(1);
for j = 2:length(x)
runningTotal(j) =
runningTotal(j-1) + x(j);
end
c. computes the sine of the given xvalues (should be a vector)
s = zeros(size(x));
for j = 1:length(x)
s(j) = sin(x(j));
end
2. Create an M-by-N array of random
numbers (use rand). Move through the
array, element by element, and set any
value that is less than 0.2 to 0 and

any value that is greater than (or


equal to) 0.2 to 1.

4. These code snippets do the job


but their repeated use is much more
interesting.

A = rand(4,7);

An example is given for

the first exercise.

[M,N] = size(A);
for j = 1:M

a. total = 0;

for k = 1:N
if A(j,k) < 0.2
A(j,k) = 0;

initialize current sum (the test


variable)
count = 0;

else
A(j,k) = 1;

initialize the counter (output of the


program)

end

while total < 20

end

% loop

until 20 is exceeded

end

count = count + 1; %
3. Given x = [4 1 6] and y = [6 2 7],
compute the following arrays
a. aij = xiyj
b. bij = xi/yj
c. ci = xiyi, then add up the
elements of c.
d. dij = xi/(2 + xi + yj)
e. eij = reciprocal of the lesser of
xi and yj

another loop repeat => another number


added
x = rand(1,1);
total = total + x; %
modify the test variable!
end
disp(['It took
',int2str(count),' numbers this

x = [4 1 6], y = [6 2 7]

time.'])

N = length(x);
for j = 1:N

--------------------------------------

c(j) = x(j)*y(j);

----------------------

for k = 1:N
a(j,k) = x(j)*y(k);
b(j,k) = x(j)/y(k);
d(j,k) = x(j)/(2 + x(j) +
y(k));
e(j,k) = 1/min(x(j),y(k));
end

loop

the above code in a for-loop.


Some simple (though perhaps
subtle) changes are needed wth respect
to retaining the counts for
each repeat.

end
c = sum(c);

To do this many times, place

% or use 1.a.

Also, the summary has

been changed from a single


text message to a histogram.
Nrep = 1000;

% collect 1000

repeats of the above code

count = zeros(Nrep,1);
for j = 1:Nrep

c. count = 0;

total = 0;

reset the test variable each repeat!!!

avg = 0;

% test

variable

while total < 20

while abs(avg - 0.5) > 0.01

count(j) = count(j) +

count = count + 1;

1; % use a vector to capture each


result

% The following line is one


total = total +

way to update the average.

rand(1,1);

% (count-1)*avg is the sum of


end

the first count-1 numbers

end

% and rand just adds another


number.

hist(count,min(count):max(count))

Dividing by count
% then gives the new average.

xlabel('Number of random
numbers from U(0,1) added to make 20')
ylabel('Count')

avg = ((count-1)*avg +
rand(1,1))/count;

title(['Histogram of results

% modify the test

var.

for ',int2str(Nrep),' repeats'])


% There are other ways to do
this and you are encouraged
--------------------------------------

% to come up with them

---------------------end
b. count = 0;
while 1

disp(['It took
%

infinite loop use

',int2str(count),' numbers this


time.'])

count = count + 1;
x = rand(1,1);
% get a number
if (x < 0.85) & (x > 0.8)
% check the value
break
% bail out if in selected range
end
end
disp(['It took
',int2str(count),' numbers this
time.'])

5. while 1

% use of an infinite

loop
TinF = input('Temperature in
F: ');

% get input
if isempty(TinF)

% how to get out


break
end
TinC = 5*(TinF - 32)/9;
% conversion
disp(' ')

disp([' ==> Temperature in C


= ',num2str(TinC)])
disp(' ')
end

In this last exercise, y = 4x for any


input!

Relational operations are

subject to precedence and ordering


just as arithmetical operations.

IF-block Exercises

logical phrase a < x < b should be


rendered as the compound logical

1. n = 7

gives m = 8

n = 9

gives m = -1

expression ((a < x) & (x < b)) in


MATLAB.

n = -10 gives m = -11

Programming Exercises
2. z = 1

gives w = 2

z = 9

gives w = 0

z = 60

gives w = sqrt(60)

z = 200 gives w = 200


3. T = 50 gives h = 0
T = 15 gives h = 31
T =

0 gives h = 1

4. x = -1

gives y = -4

x = 5

gives y = 20

x = 30

gives y = 120

x = 100 gives y = 400

The

1.
x=0;
for i=1:1000
x=x+(1/((((2*i)-1)^2)*(((2*i)
+1)^2)));
z=sqrt((x*16)+8);
error=abs(z-pi);
if (error < 10^-8)
i
break
end
end
i =
174

You might also like