Matlab Tutorials | Examples
Practice 13:
Number of rectangles from unit squares
Assume you are given an m×n rectangle of unit squares. Within this rectangle, many rectangles and squares can be formed by joining the unit squares.
Consider the 2×3 rectangle below.
There are 18 rectangles (some of them being squares) that you can construct using it:
A, AB, ABC, AD, ABDE, ABCDEF, B, BC, BE, BCEF, C, CF, D, DE, DEF, E, EF, F
Write a MATLAB program that gets the values m and n from the user. If either m or n is not a positive integer number, then the program should ask for that number again, until an acceptable value is given. The program should then count the number of rectangles/squares within the given m×n rectangle using loops, and display this number.
Solutions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
clc clear %%Inputs for dimension of the rectangles m = input('Enter m '); while(m<0) || (m~=ceil(m)) %Checking the positive integer or not disp('The value must be a positive integer.') m = input('Enter m '); end n = input('Enter n '); while(n<0) || (n~=ceil(n))%Checking the positive integer or not disp('The value must be a positive integer.') n = input('Enter n '); end %Calculating the numbers of the rectangle with in the for loop total=0; for i=1:m for j=1:n total = total + i*j; end end fprintf('Total number of rectangles inside a %gx%g rectangle of unit squares: %g\n',m,n,total); %%Calculating the numbers of the rectangle with using Mathematical Formula y = (1/4)*m*n*(m+1)*(n+1); fprintf('Total number of rectangles inside a %gx%g rectangle of unit squares: %g (Using Mathematical Formula)\n',m,n,y); |