MATLAB – Chapter 2 Exercises
Question → Script → Input → Output
Simple notebook-style solutions for Chapter 2
Question 1: Write a script to determine sin(x) at ten equally spaced values from −π ≤ x
≥ π.
Script:
clc;
clear;
x = linspace(-pi,pi,10);
y = sin(x);
disp(x)
disp(y)
Input:
x = linspace(-pi,pi,10);
Output:
x =
-3.1416 -2.4435 -1.7453 -1.0472 -0.3491 0.3491 1.0472 1.7453 2.4435 3.1416
y =
0 -0.6428 -0.9848 -0.8660 -0.3420 0.3420 0.8660 0.9848 0.6428 0.0000
Question 2: Write a script to construct the following matrix and find the required
elements.
A = [3 5 7 9 11;
20.0 20.25 20.5 20.75 21.0;
1 1 1 1 1]
Script:
clc;
clear;
A = [3 5 7 9 11;
20.0 20.25 20.5 20.75 21.0;
1 1 1 1 1];
a = A(1,1);
b = A(3,4);
c = A(:,2);
d = A(2,:);
e = A(1:3,3:5);
f = 4*ones(size(A));
disp(A)
disp(a)
disp(b)
disp(c)
disp(d)
disp(e)
disp(f)
Input:
A = [3 5 7 9 11;
MATLAB Chapter 2 | Page 1
20.0 20.25 20.5 20.75 21.0;
1 1 1 1 1]
Output:
A =
3.0000 5.0000 7.0000 9.0000 11.0000
20.0000 20.2500 20.5000 20.7500 21.0000
1.0000 1.0000 1.0000 1.0000 1.0000
a = 3
b = 1
c =
5.0000
20.2500
1.0000
d =
20.0000 20.2500 20.5000 20.7500 21.0000
e =
7.0000 9.0000 11.0000
20.5000 20.7500 21.0000
1.0000 1.0000 1.0000
f =
4 4 4 4 4
4 4 4 4 4
4 4 4 4 4
MATLAB Chapter 2 | Page 2
Question 3: Write a script to generate the given special 9 × 9 matrix.
Script:
clc;
clear;
A = [0 1 1 0 2 2 0 3 3;
1 0 1 2 0 2 3 0 3;
1 1 0 2 2 0 3 3 0;
0 4 4 0 5 5 0 6 6;
4 0 4 5 0 5 6 0 6;
4 4 0 5 5 0 6 6 0;
0 7 7 0 8 8 0 9 9;
7 0 7 8 0 8 9 0 9;
7 7 0 8 8 0 9 9 0];
disp(A)
Input:
The matrix values are entered in the script as shown above.
Output:
A =
0 1 1 0 2 2 0 3 3
1 0 1 2 0 2 3 0 3
1 1 0 2 2 0 3 3 0
0 4 4 0 5 5 0 6 6
4 0 4 5 0 5 6 0 6
4 4 0 5 5 0 6 6 0
0 7 7 0 8 8 0 9 9
7 0 7 8 0 8 9 0 9
7 7 0 8 8 0 9 9 0
Question 4: Write a script for vector exponential using dot (.) operation for x = 2 and y
= 2k, where k is from 2 to 8.
Script:
clc;
clear;
k = 2:8;
x = 2*ones(size(k));
y = 2*k;
z = x.^y;
disp(y)
disp(z)
Input:
k = 2:8
x = 2
y = 2*k
Output:
y =
4 6 8 10 12 14 16
z =
16 64 256 1024 4096 16384 65536
MATLAB Chapter 2 | Page 3
Question 5: Write a script to solve the following system of equations:
8x1 + x2 + 6x3 = 7.5
3x1 + 5x2 + 7x3 = 4
4x1 + 9x2 + 2x3 = 12
Script:
clc;
clear;
A = [8 1 6;
3 5 7;
4 9 2];
b = [7.5; 4; 12];
x = A\b;
disp(x)
Input:
A = [8 1 6;
3 5 7;
4 9 2]
b = [7.5; 4; 12]
Output:
x =
1.2931
0.8972
-0.6236
Therefore: x₁ = 1.2931, x₂ = 0.8972, x₃ = −0.6236.
MATLAB Chapter 2 | Page 4