MATLAB Excercises
MATLAB Excercises
These exercises should help you to get used to vector and matrix notation in MATLAB,
indexing, matrix and element-wise operations. Do not use any loops (for, while) or if-else
statements. Find general solutions, not solutions for the given examples.
3. Create matrix 3 by 3 with all ones. Create matrix 8 by 1 with all zeros. Create
matrix 5 by 2 with all elements equal to 0.37.
5. Create a vector x = [3, 1, 2, 5, 4]. From x create y containing the same elements
in the reverse order, find indices of elements greater than 2, create z containing
elements of x which are smaller than 4.
8. Given the same matrix m = [1, 2, 3; 2, 1, 5; 4, 6, 4; 2, 3, 2], create matrix n with rows
sorted in a descending order of elements in the second column.
Example: 1 2 3 4 6 4
2 1 5 => 2 3 2
4 6 4 1 2 3
2 3 2 2 1 5
9. Calculate the outer product of two vectors x = [1, 2, 3] and y = [0.1, 0.2, 0.3]. Mul-
tiply these two vectors element by element.
10. Given vector a = [8, 6, 4] and integer number n = 4 create matrix b containing
n-times a(1) in the first row, n-times a(2) in the second row, etc.
(i.e. b = [8, 8, 8, 8; 6, 6, 6, 6; 4, 4, 4, 4]).
11. Given matrix a = [0, 2, 1; 3, 1, 0; 4, 6, 4; 2, 0, 2], create a matrix with 1’s at locations
where a has zeros and 0’s elsewhere. Create a matrix containing all 0’s except the
maximum elements in each row of a (i.e. b = [0, 2, 0; 3, 0, 0; 0, 6, 0; 2, 0, 2]).
12. Given a vector x = [3, 1, 4] and integer number n = 5, create vector y containing
n-times x(1), n-times x(2), etc. (i.e., y = [3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 4, 4, 4, 4, 4]).
13. Evaluate a function of two variables z = y + x.e−3|y| over the range x = −1 : 0.1 : 1,
y = −1 : 0.1 : 1. Plot a 3-D mesh surface and a contour plot of this function.
14. Z is an NxM matrix which contains integers from 1 to 255 (an image, perhaps).
There are only K unique integers in the matrix (K < 255). Write a function
that maps the integers in the the matrix from the range (1, 255) to (1, K) while
preserving the order of the numbers (see the example below). This operation is
similar to compressing the colormap of an image.
Example: 1 10 25 1 2 3
123 233 255 => 5 8 9
172 201 54 6 7 4