0% found this document useful (0 votes)
27 views9 pages

MATLAB Programming Exercises Guide

The document contains a series of programming exercises primarily focused on MATLAB, including tasks such as finding maximum values in matrices, verifying properties of magic matrices, counting positive integers, and manipulating matrix elements. Each exercise includes specific input and output requirements, as well as example code snippets. Solutions for the exercises are also provided, demonstrating various programming techniques and MATLAB functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views9 pages

MATLAB Programming Exercises Guide

The document contains a series of programming exercises primarily focused on MATLAB, including tasks such as finding maximum values in matrices, verifying properties of magic matrices, counting positive integers, and manipulating matrix elements. Each exercise includes specific input and output requirements, as well as example code snippets. Solutions for the exercises are also provided, demonstrating various programming techniques and MATLAB functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Additional programming exercises

Timoteo Dinelli∗, Marco Mehl†

INFO
Solutions can be found on WeBEEP and GitHub.

Exercises
1. Write a function that finds the maximum value and its position, in terms of row and column number,
of the matrix M = magic(234) and compare the result obtained with the MATLAB builtin function
max() and find().
2. Write a MATLAB script that proves that the magic matrix definition is correct. And compare the
result with a randomly generated one.
3. Write a function that, taken as input an array A of n integers, returns its number of positive
elements, without using predefined MATLAB library functions. For example:
Input: A = [1, 5, -3, -9];
Output: ans = 2
4. Given a randomly generated matrix 8 × 8 substitute, within the matrix, the central 4 × 4 submatrix
with a matrix where all the elements are equal to one.
Input:
 
0.1981 0.4228 0.5391 0.5612 0.8555 0.2262 0.9827 0.2607
0.4897 0.5479 0.6981 0.8819 0.6448 0.3846 0.7302 0.5944
 
0.3395 0.9427 0.6665 0.6692 0.3763 0.5830 0.3439 0.0225
 
0.9516 0.4177 0.1781 0.1904 0.1909 0.2518 0.5841 0.4253
A=
0.9203

 0.9831 0.1280 0.3689 0.4283 0.2904 0.1078 0.3127

0.0527 0.3015 0.9991 0.4607 0.4820 0.6171 0.9063 0.1615
 
0.7379 0.7011 0.1711 0.9816 0.1206 0.2653 0.8797 0.1788
0.2691 0.6663 0.0326 0.1564 0.5895 0.8244 0.8178 0.4229

Output:
 
0.1981 0.4228 0.5391 0.5612 0.8555 0.2262 0.9827 0.2607
0.4897 0.5479 0.6981 0.8819 0.6448 0.3846 0.7302 0.5944
 
0.3395 0.9427 1 1 1 1 0.3439 0.0225
 
0.9516 0.4177 1 1 1 1 0.5841 0.4253
A∗ = 
0.9203

 0.9831 1 1 1 1 0.1078 0.3127

0.0527 0.3015 1 1 1 1 0.9063 0.1615
 
0.7379 0.7011 0.1711 0.9816 0.1206 0.2653 0.8797 0.1788
0.2691 0.6663 0.0326 0.1564 0.5895 0.8244 0.8178 0.4229

5. Given a square matrix A. We want to create a matrix B equal to the matrix A while replacing only
the elements on the main diagonal with the average value of the corresponding rows.

∗ [Link]@[Link]
† [Link]@[Link]

1
Programming exercises Calcoli di Processo dell’Ingegneria Chimica

Input:  
1 2 3
A = 4 5 6
7 8 9

Output:  
2 2 3
B = 4 5 6
7 8 8

6. Given a square matrix A. You want to create a matrix B containing below the main diagonal all
null elements, above the main diagonal all elements equal to the sum of all elements of matrix A,
and on the main diagonal the corresponding elements of matrix A.
Input:  
1 2 3
A = 4 5 6
7 8 9

Output:  
1 45 45
B = 0 5 45
0 0 9

7. Write a function that given a random vector returns the same vector but with the elements sorted
in ascending order, by implementing a simple version of the bubble sort algorithm (reference).
Pseudo code:
0. procedure BubbleSort(A:lista of elements to be sorted)
1. change is true
2. while scambio do
3. change is false
4. for i = 0 to length(A)-1 do
5. if A[i] ¿ A[i+1] then
6. swap( A[i], A[i+1] )
7. change is true
Input: v = [5, 4, 6, 8, 11];
Output: ans = [4, 5, 6, 8, 11]

8. Write a function that takes two integers a and b (where a < b) and returns a vector containing all
prime numbers in the range [a, b]. Implement your own logic to check if a number is prime without
using built-in functions.
Input: a = 10, b = 30
Output: ans = [11, 13, 17, 19, 23, 29]
9. Write a function that takes a square matrix as input and returns a vector containing all elements
of the matrix read in a spiral pattern (clockwise from outside to inside).
Input:  
1 2 3 4
5 6 7 8
A=
 
9 10 11 12
13 14 15 16

Output: ans = [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10]
10. Write a function that takes a vector v and a window size k as inputs and returns a new vector
where each element is the average of k consecutive elements centered at that position. For edge
elements, use only the available neighbors.
Input: v = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: ans = [1.5, 2, 3, 4, 5, 6, 6.5]

Explanation:

Academic Year 2025-2026 Page 2


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

• Position 1: avg(1,2) = 1.5


• Position 2: avg(1,2,3) = 2
• Position 3: avg(2,3,4) = 3
• ...
• Position 7: avg(6,7) = 6.5
11. Write a function that:
• Takes a square matrix A as input
• Creates three versions: rotated 90°, 180°, and 270° clockwise (implement rotation manually
with loops, don’t use rot90)
• Returns which rotation (if any) makes the matrix symmetric
• If none produce a symmetric matrix, return 0
Input:  
1 2 3
A = 4 5 6
7 8 9

Check if A rotated by 90°, 180°, or 270° is symmetric (B = B T )


Output: ans = 0 (none are symmetric)

Academic Year 2025-2026 Page 3


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

Solutions
Exercise 1: Finding maximum value and position in magic matrix

1 function [max_val, row, col] = find_max_magic()


2 % Create magic matrix
3 M = magic(234);
4
5 % Manual approach - initialize variables
6 max_val = M(1,1);
7 row = 1;
8 col = 1;
9
10 % Loop through all elements
11 [n_rows, n_cols] = size(M);
12 for i = 1:n_rows
13 for j = 1:n_cols
14 if M(i,j) > max_val
15 max_val = M(i,j);
16 row = i;
17 col = j;
18 end
19 end
20 end
21
22 fprintf('Manual approach:\n');
23 fprintf('Maximum value: %d at position (%d, %d)\n', max_val, row, col);
24
25 % Using MATLAB built-in functions
26 [max_cols, row_indices] = max(M);
27 [max_val_builtin, col_idx] = max(max_cols);
28 row_builtin = row_indices(col_idx);
29 col_builtin = col_idx;
30
31 fprintf('\nBuilt-in approach (max):\n');
32 fprintf('Maximum value: %d at position (%d, %d)\n', ...
33 max_val_builtin, row_builtin, col_builtin);
34
35 % Using find
36 [r, c] = find(M == max_val_builtin);
37 fprintf('\nUsing find:\n');
38 fprintf('Maximum value: %d at position (%d, %d)\n', ...
39 max_val_builtin, r(1), c(1));
40 end

Exercise 2: Proving magic matrix definition

1 % Script to verify magic matrix properties


2 n = 5; % Size of magic matrix
3 M = magic(n);
4
5 fprintf('Testing magic matrix of size %dx%d\n\n', n, n);
6
7 % Calculate the magic constant
8 magic_constant = n * (nˆ2 + 1) / 2;
9 fprintf('Expected magic constant: %.0f\n\n', magic_constant);
10
11 % Check row sums
12 fprintf('Row sums:\n');
13 row_sums = sum(M, 2);
14 for i = 1:n
15 fprintf('Row %d: %.0f\n', i, row_sums(i));
16 end
17
18 % Check column sums
19 fprintf('\nColumn sums:\n');
20 col_sums = sum(M, 1);
21 for i = 1:n
22 fprintf('Column %d: %.0f\n', i, col_sums(i));
23 end
24
25 % Check diagonal sums
26 main_diag_sum = sum(diag(M));
27 anti_diag_sum = sum(diag(fliplr(M)));
28 fprintf('\nMain diagonal sum: %.0f\n', main_diag_sum);

Academic Year 2025-2026 Page 4


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

29 fprintf('Anti-diagonal sum: %.0f\n', anti_diag_sum);


30
31 % Verify all sums are equal
32 is_magic = all(row_sums == magic_constant) && ...
33 all(col_sums == magic_constant) && ...
34 main_diag_sum == magic_constant && ...
35 anti_diag_sum == magic_constant;
36
37 fprintf('\nIs magic matrix valid? %s\n\n', mat2str(is_magic));
38
39 % Compare with random matrix
40 R = randi([1, nˆ2], n, n);
41 fprintf('Random matrix row sums: %s\n', mat2str(sum(R, 2)'));
42 fprintf('Random matrix column sums: %s\n', mat2str(sum(R, 1)));
43 fprintf('Random matrix is NOT magic!\n');

Exercise 3: Count positive elements

1 function count = count_positive(A)


2 % Count positive elements without using built-in functions
3 count = 0;
4 n = length(A);
5
6 for i = 1:n
7 if A(i) > 0
8 count = count + 1;
9 end
10 end
11 end
12
13 % Test the function
14 A = [1, 5, -3, -9];
15 result = count_positive(A);
16 fprintf('Number of positive elements: %d\n', result);

Exercise 4: Replace central 4x4 submatrix

1 % Generate random 8x8 matrix


2 A = rand(8, 8);
3
4 fprintf('Original matrix:\n');
5 disp(A);
6
7 % Replace central 4x4 submatrix with ones
8 % Central 4x4 is from rows 3:6 and columns 3:6
9 A(3:6, 3:6) = ones(4, 4);
10
11 fprintf('\nModified matrix:\n');
12 disp(A);

Exercise 5: Replace diagonal with row averages

1 function B = diagonal_row_average(A)
2 % Create copy of matrix A
3 B = A;
4 n = size(A, 1);
5
6 % Replace each diagonal element with its row average
7 for i = 1:n
8 row_avg = sum(A(i, :)) / n;
9 B(i, i) = row_avg;
10 end
11 end
12
13 % Test the function
14 A = [1 2 3; 4 5 6; 7 8 9];
15 B = diagonal_row_average(A);
16 fprintf('Original matrix A:\n');
17 disp(A);
18 fprintf('Modified matrix B:\n');

Academic Year 2025-2026 Page 5


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

19 disp(B);

Exercise 6: Upper triangular with sum

1 function B = create_special_matrix(A)
2 n = size(A, 1);
3 B = zeros(n, n);
4
5 % Calculate sum of all elements
6 total_sum = sum(A(:));
7
8 % Fill the matrix
9 for i = 1:n
10 for j = 1:n
11 if i == j
12 % Diagonal: keep original elements
13 B(i, j) = A(i, j);
14 elseif i < j
15 % Above diagonal: use total sum
16 B(i, j) = total_sum;
17 else
18 % Below diagonal: zeros (already initialized)
19 B(i, j) = 0;
20 end
21 end
22 end
23 end
24
25 % Test the function
26 A = [1 2 3; 4 5 6; 7 8 9];
27 B = create_special_matrix(A);
28 fprintf('Original matrix A:\n');
29 disp(A);
30 fprintf('Modified matrix B:\n');
31 disp(B);

Exercise 7: Bubble sort

1 function sorted_vec = bubble_sort(v)


2 n = length(v);
3 sorted_vec = v;
4 change = true;
5
6 while change
7 change = false;
8 for i = 1:(n-1)
9 if sorted_vec(i) > sorted_vec(i+1)
10 % Swap elements
11 temp = sorted_vec(i);
12 sorted_vec(i) = sorted_vec(i+1);
13 sorted_vec(i+1) = temp;
14 change = true;
15 end
16 end
17 end
18 end
19
20 % Test the function
21 v = [5, 4, 6, 8, 11];
22 sorted_v = bubble_sort(v);
23 fprintf('Original vector: %s\n', mat2str(v));
24 fprintf('Sorted vector: %s\n', mat2str(sorted_v));

Exercise 8: Prime numbers in range

1 function primes = find_primes(a, b)


2 primes = [];
3
4 for num = a:b
5 if is_prime(num)
6 primes = [primes, num];

Academic Year 2025-2026 Page 6


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

7 end
8 end
9 end
10
11 function result = is_prime(n)
12 % Check if n is prime
13 if n < 2
14 result = false;
15 return;
16 end
17
18 if n == 2
19 result = true;
20 return;
21 end
22
23 if mod(n, 2) == 0
24 result = false;
25 return;
26 end
27
28 % Check odd divisors up to sqrt(n)
29 for i = [Link]sqrt(n)
30 if mod(n, i) == 0
31 result = false;
32 return;
33 end
34 end
35
36 result = true;
37 end
38
39 % Test the function
40 a = 10;
41 b = 30;
42 primes = find_primes(a, b);
43 fprintf('Prime numbers between %d and %d: %s\n', a, b, mat2str(primes));

Exercise 9: Spiral matrix traversal

1 function spiral_vec = spiral_traversal(A)


2 n = size(A, 1);
3 spiral_vec = [];
4
5 top = 1;
6 bottom = n;
7 left = 1;
8 right = n;
9
10 while top <= bottom && left <= right
11 % Traverse right along top row
12 for col = left:right
13 spiral_vec = [spiral_vec, A(top, col)];
14 end
15 top = top + 1;
16
17 % Traverse down along right column
18 for row = top:bottom
19 spiral_vec = [spiral_vec, A(row, right)];
20 end
21 right = right - 1;
22
23 % Traverse left along bottom row (if still valid)
24 if top <= bottom
25 for col = right:-1:left
26 spiral_vec = [spiral_vec, A(bottom, col)];
27 end
28 bottom = bottom - 1;
29 end
30
31 % Traverse up along left column (if still valid)
32 if left <= right
33 for row = bottom:-1:top
34 spiral_vec = [spiral_vec, A(row, left)];
35 end
36 left = left + 1;

Academic Year 2025-2026 Page 7


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

37 end
38 end
39 end
40
41 % Test the function
42 A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
43 spiral = spiral_traversal(A);
44 fprintf('Original matrix:\n');
45 disp(A);
46 fprintf('Spiral traversal: %s\n', mat2str(spiral));

Exercise 10: Running average filter

1 function result = running_average(v, k)


2 n = length(v);
3 result = zeros(1, n);
4 half_window = floor(k / 2);
5
6 for i = 1:n
7 % Determine the valid window range
8 start_idx = max(1, i - half_window);
9 end_idx = min(n, i + half_window);
10
11 % Calculate average of elements in window
12 window_elements = v(start_idx:end_idx);
13 result(i) = sum(window_elements) / length(window_elements);
14 end
15 end
16
17 % Test the function
18 v = [1, 2, 3, 4, 5, 6, 7];
19 k = 3;
20 filtered = running_average(v, k);
21 fprintf('Original vector: %s\n', mat2str(v));
22 fprintf('Window size: %d\n', k);
23 fprintf('Filtered vector: %s\n', mat2str(filtered));

Exercise 11: Matrix rotation and symmetry check

1 function rotation_angle = check_rotation_symmetry(A)


2 % Returns 90, 180, 270 if that rotation produces symmetric matrix
3 % Returns 0 if none produce a symmetric matrix
4
5 % Rotate 90 degrees clockwise
6 A_90 = rotate_90(A);
7 if is_symmetric(A_90)
8 rotation_angle = 90;
9 return;
10 end
11
12 % Rotate 180 degrees
13 A_180 = rotate_90(A_90);
14 if is_symmetric(A_180)
15 rotation_angle = 180;
16 return;
17 end
18
19 % Rotate 270 degrees
20 A_270 = rotate_90(A_180);
21 if is_symmetric(A_270)
22 rotation_angle = 270;
23 return;
24 end
25
26 rotation_angle = 0;
27 end
28
29 function rotated = rotate_90(A)
30 % Rotate matrix 90 degrees clockwise manually
31 n = size(A, 1);
32 rotated = zeros(n, n);
33
34 for i = 1:n

Academic Year 2025-2026 Page 8


Programming exercises Calcoli di Processo dell’Ingegneria Chimica

35 for j = 1:n
36 rotated(j, n+1-i) = A(i, j);
37 end
38 end
39 end
40
41 function result = is_symmetric(A)
42 % Check if matrix is symmetric (A == A')
43 n = size(A, 1);
44 result = true;
45
46 for i = 1:n
47 for j = 1:n
48 if A(i, j) ˜= A(j, i)
49 result = false;
50 return;
51 end
52 end
53 end
54 end
55
56 % Test the function
57 A = [1 2 3; 4 5 6; 7 8 9];
58 angle = check_rotation_symmetry(A);
59 fprintf('Original matrix:\n');
60 disp(A);
61 fprintf('Rotation that produces symmetry: %d degrees\n', angle);
62 if angle == 0
63 fprintf('(None produce a symmetric matrix)\n');
64 end

Academic Year 2025-2026 Page 9

Common questions

Powered by AI

Determine all prime numbers within a specified range in MATLAB by iterating over each number in the range and checking its primality. Implement a primality test function that checks for divisibility by any integer up to the square root of the number. This involves looping from 2 to sqrt(n) and testing for factors. If no divisors are found, the number is prime. Collect and output this sequence of prime numbers .

Extract elements from a matrix in a spiral pattern in MATLAB by defining top, bottom, left, and right boundaries. Traverse the matrix boundary selecting elements in a clockwise direction, updating these boundaries accordingly: iterate right across the top row, down the right column, left on the bottom row (if still valid), and up the left column. Continue adjusting these boundaries inward until all matrix elements are collected in a spiral order .

To construct a matrix in MATLAB where elements below the main diagonal are null and those above are filled with the sum of the matrix's elements, first calculate the sum of all elements using the 'sum(A(:))' function. Initialize a square matrix of zeros. Iterate over the matrix elements, checking their positions relative to the main diagonal. Keep diagonal elements from the original matrix and fill elements above this diagonal with the total sum, leaving elements below as zero .

A bubble sort algorithm can be implemented in MATLAB by creating a loop that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. Begin with a 'change' flag set to true and iterate through the list until no swaps are needed (change becomes false). For each pass, sequentially compare each adjacent pair of elements, swapping them if necessary, until the entire list is ordered .

To find the maximum value and its position in a large matrix without using built-in functions in MATLAB, one can iterate through each element of the matrix while keeping track of the maximum value encountered and its position. Start by initializing the maximum value to the first element of the matrix, then loop through each element comparing it to the current maximum. If a larger value is found, update the maximum value and its position. This ensures that after checking all elements, the maximum value and its position are accurately identified .

To verify if a square matrix is a magic matrix in MATLAB, calculate the magic constant based on the matrix size, which is determined by the formula n * (n^2 + 1) / 2. Check if all row, column, and diagonal sums equal the magic constant. If they do, the matrix is considered a magic matrix. For comparison, generate a random matrix of the same size, calculate its row and column sums, and demonstrate that these are not equal to a constant, thereby proving the random matrix is not magic .

To replace the main diagonal elements of a matrix with row averages in MATLAB, first compute the average of each row by summing its elements and dividing by the number of columns. Then, create a new matrix, copying original elements and replacing each diagonal element with the corresponding row average. This process requires a loop iterating over each row and modifying the diagonal entry of the matrix .

Compute the running average of vector elements in MATLAB by determining the range of indices around each element based on the window size. Use 'floor(k / 2)' to define the half-window for centering, and calculate averages by iterating through the vector, adjusting for edge cases where fewer elements are available. Compute the mean of the elements within these boundaries for each position, producing a smoothed vector .

In MATLAB, to substitute the central submatrix of a larger 8x8 matrix with a 4x4 matrix of ones, first identify the central positions, which for an 8x8 matrix are rows and columns 3 to 6. Assign each element in the specified submatrix to one. This operation is performed by directly accessing and modifying the submatrix indices, saving computation and ensuring that the central region is updated effectively .

Rotate a square matrix by 90 degrees clockwise in MATLAB by creating a new matrix and assigning elements according to the rotation rule: the element in the i-th row and j-th column of the original matrix becomes the element in the j-th row and (n+1-i)-th column of the new matrix. To check for symmetry, rotate for angles 90, 180, and 270 degrees and verify if the rotated matrix equals its transpose. Return the angle if the matrix is symmetric; otherwise, return zero .

You might also like