├── .gitignore ├── Lec11 ├── timetemp.dat ├── runsum.m ├── lec_11_1_load_and_save.m ├── lec_11_2_matrix_indexing.m └── lec_11_3_vectorization.m ├── Lec16 ├── greet.m ├── getname.m ├── local_function_demo.m ├── function_tests.m └── structures.m ├── Lec24 ├── greet.m ├── twisters.txt ├── circleinfo.m └── Lec24.m ├── Lec17 ├── gorillas-v3 │ ├── calcshootparams.m │ ├── getshootparams.m │ ├── setplayer.m │ ├── setstage.m │ ├── shoot.m │ └── gorillas.m ├── gorillas-v3-in-class-updates │ ├── getshootparams.m │ ├── calcshootparams.m │ ├── setplayer.m │ ├── setstage.m │ ├── shoot.m │ └── gorillas.m └── gorillas_v2.m ├── Lec15 ├── cyl_area.m ├── conevol.m ├── circleinfo.m ├── print_cumsum.m └── function_test.m ├── Gorillas ├── v3 │ ├── getshootparams.m │ ├── calcshootparams.m │ ├── setplayer.m │ ├── setstage.m │ ├── shoot.m │ └── gorillas.m ├── v1 │ └── gorillas.m └── v2 │ └── gorillas.m ├── Lec22 ├── twisters.txt └── file_io.m ├── Lec23 ├── aggregate.m ├── in-class-work │ ├── aggregate.m │ ├── circleinfo.m │ └── lec23.m ├── circleinfo.m └── lec23.m ├── Lec4 ├── circleinfo.m ├── circleinfo2.m └── lec_4_1_characters_strings_and_variable_types.m ├── Lec9 ├── circleinfo.m ├── in-class-work │ ├── circleinfo.m │ ├── salesstatus.m │ └── lec_9_if_statement.m ├── salesstatus.m └── lec_9_if_statement.m ├── Lec6 ├── lec_6_2_matrix_multiplication.m ├── lec_6_3_plots.m └── lec_6_1_vec_and_mat_as_function_arguments.m ├── Lec10 ├── circleinfo.m ├── in-class-work │ ├── circleinfo2.m │ ├── circleinfo.m │ └── lec_10_2.m ├── lec_10_1.m └── lec_10_2.m ├── Lec5 ├── lec_5_3_scalar_and_array_operators.m ├── lec_5_2_matrices.m └── lec_5_1_vectors.m ├── Lec21 ├── mat_files.m └── cell_arrays.m ├── lec_3_2_vectors_and_matricies_basics.m ├── lec_2_variables_and_numeric_opertors.m ├── Lec7 ├── lec_7_input_output.m ├── gorillas.m └── gorillas_v1.m ├── lec_3_1.m ├── Lec8 └── lec_8_logical_expressions_and_operators.m ├── LEC12 ├── gorillas.m └── gorillas_v1.m ├── Lec18 └── strings_in_matlab.m ├── Lec12 └── gorillas_v2.m └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | Lec11/mydata.dat 3 | -------------------------------------------------------------------------------- /Lec11/timetemp.dat: -------------------------------------------------------------------------------- 1 | 0 3 6 9 12 15 18 21 2 | 55.5 52.4 52.6 55.7 75.6 77.7 70.3 66.6 -------------------------------------------------------------------------------- /Lec16/greet.m: -------------------------------------------------------------------------------- 1 | function greet(name) 2 | % GREET prints a greeting to a person specified by the 3 | % input argument (name) 4 | 5 | fprintf('Hello %s!\n', name) 6 | 7 | end -------------------------------------------------------------------------------- /Lec24/greet.m: -------------------------------------------------------------------------------- 1 | function greet(name) 2 | % GREET prints a greeting to a person specified by the 3 | % input argument (name) 4 | 5 | fprintf('Hello %s!\n', name) 6 | 7 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3/calcshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = calcshootparams 2 | % CALCSHOOTPARAMS calculates the angle and velocity of throw returns them. 3 | 4 | angle = []; 5 | velocity = []; 6 | 7 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3/getshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = getshootparams 2 | % GETSHOOTPARAMS obtains the angle and velocity of he throw as user-inputs 3 | % and returns them. 4 | 5 | angle = []; 6 | velocity = []; 7 | 8 | end -------------------------------------------------------------------------------- /Lec16/getname.m: -------------------------------------------------------------------------------- 1 | function [firstname, lastname] = getname 2 | % GETNAME prompts for the first and last name and returns 3 | % the values entered by the user. 4 | 5 | firstname = input('Enter the first name: ', 's'); 6 | lastname = input('Enter the last name: ', 's'); 7 | 8 | end 9 | -------------------------------------------------------------------------------- /Lec15/cyl_area.m: -------------------------------------------------------------------------------- 1 | function area = cyl_area(radius, height) 2 | % CYL_AREA calculates and returns the surface area of a cylinder with a 3 | % given radius and height. 4 | 5 | circleArea = pi * radius.^2; 6 | wallArea = 2 * pi * radius * height; 7 | 8 | area = 2 * circleArea + wallArea; 9 | 10 | end -------------------------------------------------------------------------------- /Gorillas/v3/getshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = getshootparams 2 | % GETSHOOTPARAMS obtains the angle and velocity of he throw as user-inputs 3 | % and returns them. 4 | 5 | 6 | disp('You (facing east):'); 7 | angle = round(input(' Angle (degrees)? ')); 8 | velocity = round(input(' Velocity (m/s)? ')); 9 | 10 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/getshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = getshootparams 2 | % GETSHOOTPARAMS obtains the angle and velocity of he throw as user-inputs 3 | % and returns them. 4 | 5 | 6 | disp('You (facing east):'); 7 | angle = round(input(' Angle (degrees)? ')); 8 | velocity = round(input(' Velocity (m/s)? ')); 9 | 10 | end -------------------------------------------------------------------------------- /Lec22/twisters.txt: -------------------------------------------------------------------------------- 1 | Peter Piper picked a peck of pickled peppers. 2 | How much wood would a woodchuck chuck if a woodchuck could chuck wood? 3 | She sells seashells by the seashore. 4 | Nine nice night nurses nursing nicely. 5 | If a dog chews shoes, whose shoes does he choose? 6 | I thought I thought of thinking of thanking you. 7 | Fred fed Ted bread, and Ted fed Fred bread -------------------------------------------------------------------------------- /Lec24/twisters.txt: -------------------------------------------------------------------------------- 1 | Peter Piper picked a peck of pickled peppers. 2 | How much wood would a woodchuck chuck if a woodchuck could chuck wood? 3 | She sells seashells by the seashore. 4 | Nine nice night nurses nursing nicely. 5 | If a dog chews shoes, whose shoes does he choose? 6 | I thought I thought of thinking of thanking you. 7 | Fred fed Ted bread, and Ted fed Fred bread -------------------------------------------------------------------------------- /Gorillas/v3/calcshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = calcshootparams 2 | % CALCSHOOTPARAMS calculates the angle and velocity of throw returns them. 3 | 4 | disp('Kong (facing west):'); 5 | angle = randi(90); 6 | fprintf(' Angle: %d\n', angle) 7 | angle = 180 - angle; 8 | 9 | velocity = randi([1 100]); 10 | fprintf(' Velocity: %d\n', velocity) 11 | 12 | end -------------------------------------------------------------------------------- /Lec23/aggregate.m: -------------------------------------------------------------------------------- 1 | function newTotal = aggregate(val) 2 | % AGGREGATE will take a scalar value VAL and then calculates 3 | % the sum of the VALs over multiple calls to the function. 4 | % 5 | 6 | if length(val) ~= 1 7 | error('The input argument must be a scalar'); 8 | end 9 | 10 | pastTotal = 0; 11 | 12 | newTotal = pastTotal + val; 13 | 14 | pastTotal = newTotal; 15 | 16 | end -------------------------------------------------------------------------------- /Lec15/conevol.m: -------------------------------------------------------------------------------- 1 | function outarg = conevol(radius, height) 2 | % CONEVOL calculates and returns the volume of a cone with a given radius 3 | % and height. 4 | 5 | if any(radius(:) < 0) 6 | error('Radius of a cone must be positive'); 7 | end 8 | 9 | if any(height(:) < 0) 10 | error('Height of a cone must be positive'); 11 | end 12 | 13 | outarg = (pi/3) * radius.^2 .* height; 14 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/calcshootparams.m: -------------------------------------------------------------------------------- 1 | function [angle, velocity] = calcshootparams 2 | % CALCSHOOTPARAMS calculates the angle and velocity of throw returns them. 3 | 4 | disp('Kong (facing west):'); 5 | angle = randi(90); 6 | fprintf(' Angle: %d\n', angle) 7 | angle = 180 - angle; 8 | 9 | velocity = randi([1 100]); 10 | fprintf(' Velocity: %d\n', velocity) 11 | 12 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3/setplayer.m: -------------------------------------------------------------------------------- 1 | function player = setplayer(playerId) 2 | % SETPLAYER sets a player on a builing that is randomly selected between 3 | % the minBuildingIndex and maxBuildingIndex. Returns the player as a 4 | % structure. 5 | 6 | 7 | 8 | 9 | 10 | player = struct('x', [], ... 11 | 'y', [], ... 12 | 'Id', playerId, ... 13 | 'buildingId', [] ... 14 | ); 15 | end -------------------------------------------------------------------------------- /Lec4/circleinfo.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO calculates the circumference and area of a circle 2 | % and displays them. 3 | % 4 | % Author: YOUR NAME 5 | % ENCMP100 B3, Winter 2020. 6 | % Reference: Attaway, chapter 3.1 to 3.4 7 | 8 | 9 | % Radius of the circle 10 | radius = 2; 11 | 12 | % Calculating the circumference 13 | circ = 2 * pi * radius; 14 | 15 | % Calculating the area 16 | area = pi * radius^2; 17 | 18 | % Display the result 19 | circ 20 | area 21 | -------------------------------------------------------------------------------- /Lec23/in-class-work/aggregate.m: -------------------------------------------------------------------------------- 1 | function newTotal = aggregate(val) 2 | % AGGREGATE will take a scalar value VAL and then calculates 3 | % the sum of the VALs over multiple calls to the function. 4 | % 5 | 6 | persistent pastTotal; 7 | 8 | if length(val) ~= 1 9 | error('The input argument must be a scalar'); 10 | end 11 | 12 | if isempty(pastTotal) 13 | pastTotal = 0; 14 | end 15 | 16 | newTotal = pastTotal + val; 17 | 18 | pastTotal = newTotal; 19 | 20 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3/setstage.m: -------------------------------------------------------------------------------- 1 | function stage = setstage(numBuildings) 2 | % SETSTAGE initializes a new stage with the specified number of buildings 3 | % and returns the parameters of the created stage in a structure. 4 | % 5 | 6 | 7 | 8 | 9 | 10 | stage = struct('x', [], ... 11 | 'y', [], ... 12 | 'Count', numBuildings, ... 13 | 'buildingWidth', [], ... 14 | 'step', [] ... 15 | ); 16 | 17 | end -------------------------------------------------------------------------------- /Lec9/circleinfo.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO prompts for radius of a circle and then calculates its 2 | % circumference and area. Prints an error message if a negaive radius is 3 | % entered. 4 | % 5 | % Author: YOUR NAME 6 | % ENCMP100 B3, Winter 2020. 7 | 8 | 9 | % Radius of the circle 10 | radius = input ('Enter radius: '); 11 | 12 | % Calculating the circumference 13 | circ = 2 * pi * radius; 14 | 15 | % Calculating the area 16 | area = pi * radius^2; 17 | 18 | % Display the result 19 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 20 | radius, circ, area) 21 | 22 | -------------------------------------------------------------------------------- /Lec11/runsum.m: -------------------------------------------------------------------------------- 1 | % RUNSUM prompts to input a number repeatedly and computes the 2 | % sum of all numbers entered. Entering an empty input will terminate the program 3 | 4 | 5 | clc 6 | fprintf('Welcome to RUNSUM.\n') 7 | fprintf('Just hit enter to exit.\n\n') 8 | 9 | sum = 0; 10 | val = input('First number: '); 11 | 12 | while ~isempty(val) 13 | % add the current value to sum 14 | sum = sum + val; 15 | 16 | % display the sum 17 | fprintf('Sum: %0.2f\n', sum) 18 | 19 | % prompt to input the next value 20 | val = input('Next number: '); 21 | end 22 | 23 | % display a message just before exit. 24 | fprintf('See you later!\n') 25 | -------------------------------------------------------------------------------- /Lec4/circleinfo2.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO2 calculates the circumference and area of a circle 2 | % and display them. 3 | % 4 | % Author: YOUR NAME 5 | % ENCMP100 B3, Winter 2020. 6 | % Reference: Attaway, chapter 3.1 to 3.4 7 | 8 | %clear workspace and the command window 9 | clear 10 | clc 11 | 12 | % Radius of the circle 13 | radius = input('Enter Radius: '); 14 | 15 | % Calculating the circumference 16 | circ = 2 * pi * radius; 17 | 18 | % Calculating the area 19 | area = pi * radius^2; 20 | 21 | % Display the result 22 | % fprintf('Circumference of a circle with radius %.2f is %.3f\n', radius, circ); 23 | fprintf('\nRadius: %.2f\nCircumference: %.3f\nArea: %.3f\n', radius, circ, area); -------------------------------------------------------------------------------- /Lec15/circleinfo.m: -------------------------------------------------------------------------------- 1 | function [area, circumference] = circleinfo(radius) 2 | % CIRCLEINFO: This function calculates and returns the area and 3 | % circumference of a circle of a given radius. 4 | % 5 | % Input: 6 | % RADIUS: the radius, can be a scalar, vector or a matrix. If a negative 7 | % radius is provided, the function produce an error and aborts. 8 | % 9 | % Output: 10 | % AREA and CIRCUMFERENCE of the circle. They have the same dimensions as 11 | % the input RADIUS. 12 | % 13 | % ENCMP100 B3 - Winter 2020. 14 | % 15 | 16 | if any(radius < 0) 17 | error('Radius must be positive') 18 | end 19 | 20 | area = pi * radius.^2; 21 | circumference = 2 * pi * radius; 22 | 23 | end 24 | 25 | -------------------------------------------------------------------------------- /Lec23/circleinfo.m: -------------------------------------------------------------------------------- 1 | function [area, circumference] = circleinfo(radius) 2 | % CIRCLEINFO: This function calculates and returns the area and 3 | % circumference of a circle of a given radius. 4 | % 5 | % Input: 6 | % RADIUS: the radius, can be a scalar, vector or a matrix. If a negative 7 | % radius is provided, the function produce an error and aborts. 8 | % 9 | % Output: 10 | % AREA and CIRCUMFERENCE of the circle. They have the same dimensions as 11 | % the input RADIUS. 12 | % 13 | % ENCMP100 B3 - Winter 2020. 14 | % 15 | 16 | if any(radius(:) < 0) 17 | error('Radius must be positive') 18 | end 19 | 20 | area = pi * radius^2; 21 | circumference = 2 * pi * radius; 22 | 23 | end 24 | 25 | -------------------------------------------------------------------------------- /Lec24/circleinfo.m: -------------------------------------------------------------------------------- 1 | function [area, circumference] = circleinfo(radius) 2 | % CIRCLEINFO: This function calculates and returns the area and 3 | % circumference of a circle of a given radius. 4 | % 5 | % Input: 6 | % RADIUS: the radius, can be a scalar, vector or a matrix. If a negative 7 | % radius is provided, the function produce an error and aborts. 8 | % 9 | % Output: 10 | % AREA and CIRCUMFERENCE of the circle. They have the same dimensions as 11 | % the input RADIUS. 12 | % 13 | % ENCMP100 B3 - Winter 2020. 14 | % 15 | 16 | if any(radius(:) < 0) 17 | error('Radius must be positive') 18 | end 19 | 20 | area = pi * radius.^2; 21 | circumference = 2 * pi * radius; 22 | 23 | end 24 | 25 | -------------------------------------------------------------------------------- /Lec6/lec_6_2_matrix_multiplication.m: -------------------------------------------------------------------------------- 1 | % Lecture 6 Part 2 - Matrix multiplication 2 | % Chapter 2.5 Attaway 3 | 4 | 5 | % multiplication of two matricies 6 | mat1 = randi(5,3,4) % 3x4 matrix 7 | mat2 = randi(5,4,3) % 4x3 matrix 8 | 9 | mat1 * mat2 % results a 3x3 matrix 10 | 11 | mat2 * mat1 % results a 4x4 matrix 12 | 13 | 14 | 15 | % multiplication between a vector and a matrix 16 | vec = randi(5,1,3) % 3 element row vector 17 | mat = randi(5,3,4) % 3x4 matrix 18 | 19 | vec * mat % results a 1x4 row vector 20 | 21 | % dot product between a row vector and a column vector 22 | v1 = [1:4] % 1x4 row vector 23 | v2 = randi(5,4,1) % 4x1 column vector 24 | 25 | v1*v2 26 | dot(v1,v2) 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Lec10/circleinfo.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO prompts for radius of a circle and then calculates its 2 | % circumference and area. Prints an error message if a negaive radius is 3 | % entered. 4 | % 5 | % Author: YOUR NAME 6 | % ENCMP100 B3, Winter 2020. 7 | 8 | 9 | % Radius of the circle 10 | radius = input ('Enter radius: '); 11 | 12 | if radius > 0 13 | 14 | % Calculating the circumference 15 | circ = 2 * pi * radius; 16 | 17 | % Calculating the area 18 | area = pi * radius^2; 19 | 20 | % Display the result 21 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 22 | radius, circ, area) 23 | 24 | else 25 | error('Invalid input.') 26 | 27 | end 28 | 29 | -------------------------------------------------------------------------------- /Lec23/in-class-work/circleinfo.m: -------------------------------------------------------------------------------- 1 | function [area, circumference] = circleinfo(radius) 2 | % CIRCLEINFO: This function calculates and returns the area and 3 | % circumference of a circle of a given radius. 4 | % 5 | % Input: 6 | % RADIUS: the radius, can be a scalar, vector or a matrix. If a negative 7 | % radius is provided, the function produce an error and aborts. 8 | % 9 | % Output: 10 | % AREA and CIRCUMFERENCE of the circle. They have the same dimensions as 11 | % the input RADIUS. 12 | % 13 | % ENCMP100 B3 - Winter 2020. 14 | % 15 | 16 | if any(radius(:) < 0) 17 | error('Radius must be positive') 18 | end 19 | 20 | area = pi * radius^2; 21 | circumference = 2 * pi * radius; 22 | 23 | end 24 | 25 | -------------------------------------------------------------------------------- /Lec9/in-class-work/circleinfo.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO prompts for radius of a circle and then calculates its 2 | % circumference and area. Prints an error message if a negaive radius is 3 | % entered. 4 | % 5 | % Author: YOUR NAME 6 | % ENCMP100 B3, Winter 2020. 7 | 8 | 9 | % Radius of the circle 10 | radius = input ('Enter radius: '); 11 | 12 | if radius > 0 13 | 14 | % Calculating the circumference 15 | circ = 2 * pi * radius; 16 | 17 | % Calculating the area 18 | area = pi * radius^2; 19 | 20 | % Display the result 21 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 22 | radius, circ, area) 23 | 24 | else 25 | error('Invalid input.') 26 | 27 | end 28 | 29 | -------------------------------------------------------------------------------- /Gorillas/v3/setplayer.m: -------------------------------------------------------------------------------- 1 | function player = setplayer(stage, playerId) 2 | % SETPLAYER sets a player on a builing that is randomly selected bars 3 | % t. Returns the player as a 4 | % structure. 5 | 6 | if playerId == 1 7 | index = randi([1, floor(stage.Count/2)]); 8 | elseif playerId == 2 9 | index = randi([floor(stage.Count/2) + 1, stage.Count]); 10 | else 11 | error('PlayerId must be 1 or 2'); 12 | end 13 | 14 | px = stage.x(index); 15 | py = stage.y(index) + 10; 16 | plot(px, py, 'p', 'MarkerSize', 20) 17 | 18 | 19 | 20 | 21 | player = struct('x', px, ... 22 | 'y', py, ... 23 | 'Id', playerId, ... 24 | 'buildingId', index ... 25 | ); 26 | 27 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/setplayer.m: -------------------------------------------------------------------------------- 1 | function player = setplayer(stage, playerId) 2 | % SETPLAYER sets a player on a builing that is randomly selected bars 3 | % t. Returns the player as a 4 | % structure. 5 | 6 | if playerId == 1 7 | index = randi([1, floor(stage.Count/2)]); 8 | elseif playerId == 2 9 | index = randi([floor(stage.Count/2) + 1, stage.Count]); 10 | else 11 | error('PlayerId must be 1 or 2'); 12 | end 13 | 14 | px = stage.x(index); 15 | py = stage.y(index) + 10; 16 | plot(px, py, 'p', 'MarkerSize', 20) 17 | 18 | 19 | 20 | 21 | player = struct('x', px, ... 22 | 'y', py, ... 23 | 'Id', playerId, ... 24 | 'buildingId', index ... 25 | ); 26 | 27 | end -------------------------------------------------------------------------------- /Lec10/in-class-work/circleinfo2.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO prompts for radius of a circle and then calculates its 2 | % circumference and area. Prints an error message if a negaive radius is 3 | % entered. 4 | % 5 | % Author: YOUR NAME 6 | % ENCMP100 B3, Winter 2020. 7 | 8 | clc 9 | 10 | 11 | 12 | % Radius of the circle 13 | radius = input ('Enter radius: '); 14 | 15 | while radius > 0 16 | 17 | % Calculating the circumference 18 | circ = 2 * pi * radius; 19 | 20 | % Calculating the area 21 | area = pi * radius^2; 22 | 23 | % Display the result 24 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 25 | radius, circ, area) 26 | 27 | fprintf('\n') 28 | radius = input ('Enter radius: '); 29 | end 30 | 31 | 32 | -------------------------------------------------------------------------------- /Lec5/lec_5_3_scalar_and_array_operators.m: -------------------------------------------------------------------------------- 1 | % Lecture 5 Part 3, Scalar and Array Operators 2 | % on Vectors and Matrices 3 | % Chapter 2.2 Attaway 4 | 5 | clear 6 | clc 7 | 8 | % Scalar Operations 9 | % ================= 10 | 11 | v = [3 7 2 1] 12 | v * 3 % scalar multiplication 13 | v / 2 % scalar division 14 | v + 10 % scalar addition 15 | 16 | mat = [4:6; 3:-1:1] 17 | mat * 2 % scalar multiplication 18 | mat / 4 % scalar division 19 | mat - 5 % scalar subtraction 20 | 21 | % Array (element-by-element) Operations 22 | % ===================================== 23 | 24 | v1 = 2:5 25 | v2 = [33 11 5 1] 26 | 27 | v1 + v2 28 | v1 - v2 29 | v1 .* v2 30 | v1 ./ v2 31 | 32 | 33 | mata = [5:8; 9:-2:3] 34 | matb = reshape(1:8,2,4) 35 | 36 | mata - matb 37 | mata .* matb 38 | 39 | -------------------------------------------------------------------------------- /Lec16/local_function_demo.m: -------------------------------------------------------------------------------- 1 | % Local Functions 2 | 3 | % A local function is written in a script or in the file of 4 | % another function. i.e. the local function is not saved in a 5 | % separate file with the name equals to the function name. 6 | % Local functions can only be called from the file where it is 7 | % defined. 8 | 9 | fullname = concat('John', 'Carter'); 10 | fprintf('Full name: %s\n', fullname) 11 | 12 | 13 | 14 | % TO DO: call the above concat function in the command line. 15 | % You will get an error because this LOCAL function is only 16 | % visible inside this script 17 | 18 | 19 | 20 | % Local function definition 21 | function result = concat(firstName, lastName) 22 | 23 | result = [firstName ' ' lastName]; 24 | 25 | printsomething 26 | 27 | 28 | end 29 | 30 | -------------------------------------------------------------------------------- /Lec9/salesstatus.m: -------------------------------------------------------------------------------- 1 | % This simple script prompts for the total daily sales of computers and 2 | % their sevice plans and displays apprpriate messages using 3 | % nested if/else statements. 4 | 5 | clc 6 | 7 | computerSales = input('Today''s revenue from computer sales : $'); 8 | servicePlanSales = input('Today''s revenue from service plans : $'); 9 | 10 | fprintf('\n=================================\n'); 11 | if computerSales < 50000 12 | disp('We should sell better tomorrow') 13 | else 14 | fprintf('Today''s sales are good: %d!\n', computerSales) 15 | if servicePlanSales < 10000 16 | disp('Work hard on service plans tomorrow though') 17 | else 18 | fprintf('Good money from service plans too: %d!\n', servicePlanSales) 19 | end 20 | end 21 | fprintf('\n=================================\n'); 22 | -------------------------------------------------------------------------------- /Lec10/in-class-work/circleinfo.m: -------------------------------------------------------------------------------- 1 | % CIRCLEINFO prompts for radius of a circle and then calculates its 2 | % circumference and area. Prints an error message if a negaive radius is 3 | % entered. 4 | % 5 | % Author: YOUR NAME 6 | % ENCMP100 B3, Winter 2020. 7 | 8 | clc 9 | 10 | for k = 1:5 11 | 12 | % Radius of the circle 13 | radius = input ('Enter radius: '); 14 | 15 | if radius > 0 16 | 17 | 18 | % Calculating the circumference 19 | circ = 2 * pi * radius; 20 | 21 | % Calculating the area 22 | area = pi * radius^2; 23 | 24 | % Display the result 25 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 26 | radius, circ, area) 27 | 28 | else 29 | disp('Invalid input.') 30 | 31 | end 32 | 33 | fprintf('\n') 34 | end 35 | -------------------------------------------------------------------------------- /Lec21/mat_files.m: -------------------------------------------------------------------------------- 1 | % 2 | % Saving to binary mat files and loading from them 3 | % 4 | % Reference: Attaway, Chapter 9.1 5 | % 6 | % Lecture 19. March 19, 2019 7 | % 8 | 9 | clear 10 | clc 11 | 12 | 13 | myMat = rand(5); 14 | myStr = "Hello, this is a string!"; 15 | 16 | % Saving the entire workspace to a matfile named mywork.mat 17 | save mywork 18 | 19 | 20 | % Checking the contents (variables) in the mat file 21 | who -file mywork 22 | 23 | 24 | % Appending another variable to the same file 25 | myRange = 0:2:100; 26 | save -append mywork myRange 27 | 28 | who -file mywork 29 | 30 | % Saving only one variable to a file 31 | save mywork2 myStr 32 | who -file mywork2 33 | 34 | 35 | %% Loading data from a binary MAT file 36 | 37 | % Clear the workspace, just to make sure all variables are deleted 38 | % space. 39 | clear 40 | clc 41 | whos 42 | 43 | % Loading data from the MAT ile 44 | load mywork 45 | 46 | whos -------------------------------------------------------------------------------- /Lec9/in-class-work/salesstatus.m: -------------------------------------------------------------------------------- 1 | % This simple script prompts for the total daily sales of computers and 2 | % their sevice plans and displays apprpriate messages using 3 | % nested if/else statements. 4 | 5 | clc 6 | 7 | computerSales = input('Today''s revenue from computer sales : $'); 8 | servicePlanSales = input('Today''s revenue from service plans : $'); 9 | 10 | fprintf('\n=================================\n'); 11 | if computerSales < 50000 12 | disp('We should sell better tomorrow') 13 | if servicePlanSales < 10 14 | disp('You are fired') 15 | else 16 | fprintf('Okay money from service plans: %d!\n', servicePlanSales) 17 | end 18 | else 19 | fprintf('Today''s sales are good: %d!\n', computerSales) 20 | if servicePlanSales < 10000 21 | disp('Work hard on service plans tomorrow though') 22 | else 23 | fprintf('Good money from service plans too: %d!\n', servicePlanSales) 24 | end 25 | end 26 | fprintf('\n=================================\n'); 27 | -------------------------------------------------------------------------------- /lec_3_2_vectors_and_matricies_basics.m: -------------------------------------------------------------------------------- 1 | % Lecture 3 Part 2, Basics of Vectors and Matricies 2 | % Chapter 2.1 Attaway 3 | 4 | % Row Vectors 5 | % =========== 6 | 7 | % Initializing a row vector 8 | vec1 = [1 2 3 4 5] 9 | 10 | vec2 = [1,2, 3,4,5] 11 | 12 | 13 | 14 | % using the colon operator 15 | vec3 = 0:10 16 | 17 | vec4 = 0:2:10 % 0 to 10 in increments of 2 18 | 19 | vec = 0:3:10 20 | 21 | vec5 = 10:-1:0; 22 | 23 | 24 | % Column Vectors 25 | % ============== 26 | 27 | % define column vectors by using semicolon to 28 | % separate elements, instead of 29 | % white space or comma 30 | cv1 = [1;2;3;4;5] 31 | 32 | % Alternatively, create a row vector and then use 33 | % the "transpose" operator (single quote) to 34 | % transpose it into a column vector 35 | cv2 = [1:5]' 36 | 37 | 38 | 39 | % Matricies 40 | % ========= 41 | 42 | % Defining a 2x3 matrix; use a new line for the second row 43 | mat1 = [1 2 3 44 | 4 5 6]; 45 | 46 | % we can also use a semicolon to separate rows 47 | mat2 = [1 2 3; 4 5 6] 48 | 49 | 50 | -------------------------------------------------------------------------------- /Lec16/function_tests.m: -------------------------------------------------------------------------------- 1 | %% Functions that take no arguments 2 | % ================================ 3 | % If a function does not take any input argument, you can 4 | % eliminate the input argument list along with braces. 5 | % e.g. see the getname function in getname.m 6 | 7 | clear 8 | clc 9 | 10 | [first, last] = getname; 11 | 12 | 13 | %% Commands 14 | % ======== 15 | % Functions that contains only string arguments and 16 | % not returning any values can be called as commands. 17 | % e.g. see the userdefined function greet in greet.m 18 | 19 | % function form 20 | greet('John') 21 | 22 | % command form 23 | greet John 24 | 25 | % When uncommented, the following command will thow an error 26 | % because the second word separated by the white space will 27 | % be considered as the second input argument to the function 28 | % in the command form. Note that the function "greet" only 29 | % takes one input argument. 30 | 31 | % greet John Carter 32 | 33 | % The following works because the two words are part of the same 34 | % string 35 | greet 'John Carter' 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Lec10/lec_10_1.m: -------------------------------------------------------------------------------- 1 | % Lecture 10 Part 1: "IS" functions. These are used for checking 2 | % variable "types" 3 | % Chapter 4.5 4 | 5 | %% ISEMPTY 6 | clear 7 | clc 8 | 9 | isempty(val) % This produces an error 10 | % val does not exist yet 11 | % in the workspace 12 | 13 | val = []; % Empty vector 14 | isempty(val) 15 | 16 | val = ''; % Empty string 17 | isempty(val) 18 | 19 | val = 10; 20 | isempty(val) 21 | 22 | val = 'Hello'; 23 | isempty(val) 24 | 25 | 26 | %% ISLETTER 27 | clear 28 | clc 29 | 30 | isletter(val) % This produces an error 31 | % val does not exist yet 32 | % in the workspace 33 | 34 | val = 'Hello'; 35 | isletter(val) 36 | 37 | val = 'Hello World!'; 38 | isletter(val) 39 | 40 | val = 'Hi 8'; 41 | isletter(val) 42 | 43 | val = ''; 44 | isletter(val) 45 | 46 | val = 8; 47 | isletter(val) 48 | 49 | val = [1 2 3 6]; 50 | isletter(val) 51 | 52 | %% ISA 53 | % testing data type (class) of variables 54 | clear 55 | clc 56 | 57 | doubleVal = 10; 58 | charVal = 'ABCD'; 59 | 60 | isa(doubleVal, 'double') 61 | isa(charVal, 'double') 62 | 63 | isa(doubleVal, 'char') 64 | isa(charVal, 'char') 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Gorillas/v3/setstage.m: -------------------------------------------------------------------------------- 1 | function stage = setstage(numBuildings) 2 | % SETSTAGE initializes a new stage with the specified number of buildings 3 | % and returns the parameters of the created stage in a structure. 4 | % 5 | 6 | 7 | clf % clear previously plotted figure 8 | clc 9 | 10 | % Setting up the parameters 11 | first = 25; 12 | step = 25; 13 | count = numBuildings; 14 | buildingWidth = 20; 15 | minH = 100; 16 | maxH = 200; 17 | xmax = numBuildings * (step + 2); 18 | ymax = 400; 19 | 20 | % Generating x and y vectors for the bar chart 21 | stageX = first : step : step * count; 22 | rng('shuffle') % initialize the random number generator with a clock-based seed 23 | stageY = randi([minH, maxH], 1, length(stageX)); 24 | 25 | % Plotting the chart 26 | w = buildingWidth / step; 27 | bar(stageX, stageY, w) 28 | hold on 29 | axis([0, xmax, 0, ymax]) 30 | xlabel('Position (m)'); 31 | ylabel('Height (m)'); 32 | title('{\itGorillas} in MATLAB'); 33 | 34 | 35 | 36 | 37 | stage = struct('x', stageX, ... 38 | 'y', stageY, ... 39 | 'Count', numBuildings, ... 40 | 'buildingWidth', buildingWidth, ... 41 | 'step', step ... 42 | ); 43 | 44 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/setstage.m: -------------------------------------------------------------------------------- 1 | function stage = setstage(numBuildings) 2 | % SETSTAGE initializes a new stage with the specified number of buildings 3 | % and returns the parameters of the created stage in a structure. 4 | % 5 | 6 | 7 | clf % clear previously plotted figure 8 | clc 9 | 10 | % Setting up the parameters 11 | first = 25; 12 | step = 25; 13 | count = numBuildings; 14 | buildingWidth = 20; 15 | minH = 100; 16 | maxH = 200; 17 | xmax = numBuildings * (step + 2); 18 | ymax = 400; 19 | 20 | % Generating x and y vectors for the bar chart 21 | stageX = first : step : step * count; 22 | rng('shuffle') % initialize the random number generator with a clock-based seed 23 | stageY = randi([minH, maxH], 1, length(stageX)); 24 | 25 | % Plotting the chart 26 | w = buildingWidth / step; 27 | bar(stageX, stageY, w) 28 | hold on 29 | axis([0, xmax, 0, ymax]) 30 | xlabel('Position (m)'); 31 | ylabel('Height (m)'); 32 | title('{\itGorillas} in MATLAB'); 33 | 34 | 35 | 36 | 37 | stage = struct('x', stageX, ... 38 | 'y', stageY, ... 39 | 'Count', numBuildings, ... 40 | 'buildingWidth', buildingWidth, ... 41 | 'step', step ... 42 | ); 43 | 44 | end -------------------------------------------------------------------------------- /Lec15/print_cumsum.m: -------------------------------------------------------------------------------- 1 | function print_cumsum(range) 2 | % PRINT_CUMSUM calculates and prints the cumulative sum of numbers in the 3 | % specified range. 4 | % 5 | % If the input argument range is a scalar, cumulative sum 6 | % of numbers from zero to range is calculated in steps of 1. 7 | % 8 | % If range is a vector of 2 elements, the cumulative sum is calculated 9 | % between the first and second elements of the vector in steps of 1. 10 | % 11 | % If range is a vector of 3 elements, the cumulative sum is calculated 12 | % between the first and second elements of the vector in steps specified by 13 | % the third element. 14 | % 15 | % Author: Kamal Ranaweera 16 | % Winter, 2020. 17 | 18 | switch numel(range) 19 | case 1 20 | if range > 0 21 | x = 0 : range; 22 | else 23 | x = 0 : -1 : range; 24 | end 25 | case 2 26 | if range(1) < range(2) 27 | x = range(1) : range(2); 28 | else 29 | x = range(1) : -1 : range(2); 30 | end 31 | case 3 32 | if range(1) < range(2) 33 | x = range(1) : range(3) : range(2); 34 | else 35 | x = range(1) : -abs(range(3)) : range(2); 36 | end 37 | otherwise 38 | error('Error: Input argument must be a scalar or a vector of length 2 or 3.') 39 | end 40 | 41 | y = cumsum(x); 42 | disp(y) 43 | end -------------------------------------------------------------------------------- /Lec11/lec_11_1_load_and_save.m: -------------------------------------------------------------------------------- 1 | % Introduction to File Input and Output (Load and Save) 2 | % Chapter 3.6 3 | 4 | clear 5 | clc 6 | 7 | % Saving data to a text file 8 | mat = randi(100, 4, 3); 9 | save mydata.dat mat -ascii 10 | 11 | % view the file content on the command prompt 12 | type mydata.dat 13 | 14 | % Clear the workspace and load the data 15 | clear 16 | whos 17 | 18 | load mydata.dat 19 | whos 20 | 21 | 22 | %% Appending another variable with same number of columns to the same file. 23 | mat2 = rand(3); 24 | save mydata.dat mat2 -ascii -append 25 | 26 | % view the file content 27 | type mydata.dat 28 | 29 | 30 | % clear the workspace and load the data 31 | clear 32 | whos 33 | 34 | load mydata.dat 35 | whos 36 | 37 | %% Append another variable with a different number of columns 38 | mat3 = [1 2 3 4; 5 6 7 8]; 39 | save mydata.dat mat3 -ascii -append 40 | 41 | % view the file content 42 | type mydata.dat 43 | 44 | 45 | % clear the workspace and load the data 46 | clear 47 | load mydata.dat 48 | 49 | 50 | %% An example from the book 51 | 52 | % This reads time and temperature data for an afternoon 53 | % from a file and plots the data 54 | load timetemp.dat 55 | 56 | % The times are in the first row, temps in the second row 57 | time = timetemp(1,:); 58 | temp = timetemp(2,:); 59 | 60 | % Plot the data and label the plot 61 | plot(time,temp,'k*') 62 | xlabel('Time') 63 | ylabel('Temperature') 64 | title('Temperatures one afternoon') 65 | 66 | -------------------------------------------------------------------------------- /Lec10/lec_10_2.m: -------------------------------------------------------------------------------- 1 | % Lecture 10 Part 2: FOR loops 2 | % Chapter 5.1 and 5.2 3 | 4 | 5 | %% FOR loop (iterating through a fixed number of times 6 | clc 7 | for i = 1:5 8 | fprintf('%d: Hello world\n', i); 9 | end 10 | 11 | %% FOR loop ex. #2 12 | clc 13 | vec = randi(99, 1, 5) 14 | for i = vec 15 | fprintf('%d: Hello world\n', i); 16 | end 17 | 18 | %% FOR loop ex. #3 19 | % Inputting a vector of values one by one 20 | clc 21 | vec = zeros(1, 5); % pre-allocate storage 22 | for i = 1:length(vec) 23 | vec(i) = input('Enter a number: '); 24 | end 25 | disp('You entered:') 26 | disp(vec) 27 | 28 | %% EXERCISE: Create version 3 of "circleinfo.m" which would perform the 29 | % computation for 5 times. 30 | 31 | 32 | 33 | %% Nested FOR loops 34 | clear 35 | clc 36 | 37 | for a = 1:5 38 | for b = 1:3 39 | fprintf('a=%d, b=%d: Hello world\n', a, b) 40 | end 41 | fprintf('\n') 42 | end 43 | 44 | 45 | %% Printing a triangle of stars 46 | clear 47 | clc 48 | 49 | rows = input('Enter number of rows: '); 50 | for i=1:rows 51 | % inner loop just iterates to the value of i 52 | for j=1:i 53 | fprintf('* ') 54 | end 55 | fprintf('\n') 56 | end 57 | 58 | 59 | %% 60 | % Using SIZE function to get the rows and columns 61 | % of a matrix and then iterating through 62 | % all rows and and all columns, row by row 63 | 64 | clear 65 | clc 66 | 67 | mat = randi([10, 99], 4, 3); 68 | disp(mat) 69 | 70 | [m, n] = size(mat); % SIZE function returns the 71 | % number of rows and columns 72 | for r = 1:m 73 | for c = 1:n 74 | val = mat(r,c); 75 | if val < 50 76 | fprintf('%6c', '.') 77 | else 78 | fprintf('%6c', '*') 79 | end 80 | end 81 | fprintf('\n') 82 | end 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /Lec6/lec_6_3_plots.m: -------------------------------------------------------------------------------- 1 | % Lecture 6 Part 3 Plots 2 | % Chapter 3.5 Attaway 3 | 4 | % NOTE: Please try the plot formatting options described in 5 | % Attawat page 100. 6 | 7 | % Plot Example 1 8 | % ============== 9 | % Attaway pg 95 10 | % This is a really simple plot of just one point! 11 | % Create coordinate variables and plot a red '*' 12 | x = 11; 13 | y = 48; 14 | plot(x,y,'r*') 15 | % Change the axes and label them 16 | axis([9 12 35 55]) 17 | xlabel('Time') 18 | ylabel('Temperature') 19 | % Put a title on the plot 20 | title('Time and Temp') 21 | 22 | 23 | % Plot Example 2 24 | % ============== 25 | % A line gaph 26 | clf % clearing the previous figure 27 | x = 1:6; 28 | y = [1 5 3 9 11 8]; 29 | plot(x,y) 30 | 31 | 32 | % Plot Example 3 33 | % ============== 34 | % Attaway pg 99 35 | % This creates 2 different plots, in 2 different 36 | % Figure Windows, to demonstrate some plot features 37 | close all % closing all figures 38 | x = 1:5; 39 | y1 = [2 11 6 9 3]; 40 | y2 = [4 5 8 6 2]; 41 | 42 | % Put a bar chart in Figure 1 43 | figure(1) 44 | bar(x,y1) 45 | 46 | % Put plots using different y values on one plot 47 | % with a legend 48 | figure(2) 49 | plot(x,y1,'k') % plot a line in black, using default solid line format 50 | hold on % forces the previous plot to stay when the next plot is made 51 | plot(x,y2,'ko') % plot in black, mark points in circles but with no line 52 | grid on 53 | legend('y1','y2') 54 | 55 | 56 | % Plot Example 3 57 | % ============== 58 | % Attaway pg 100 59 | 60 | % This script plots sin(x) and cos(x) in the same Figure Window 61 | % for values of x ranging from 0 to 2*pi 62 | clf 63 | x = 0: 2*pi/40: 2*pi; 64 | y = sin(x); 65 | plot(x,y,'ro') 66 | hold on 67 | y = cos(x); 68 | plot(x,y,'b+') 69 | legend('sin', 'cos') 70 | xlabel('x') 71 | ylabel('sin(x) or cos(x)') 72 | title('sin and cos on one graph') 73 | 74 | -------------------------------------------------------------------------------- /Lec11/lec_11_2_matrix_indexing.m: -------------------------------------------------------------------------------- 1 | % Here are some examples for different methods which can be used to access 2 | % matrix elements 3 | 4 | 5 | %% Ex. 1: Access the element at 3rd row, 2nd column 6 | % ================================================= 7 | mat = rand(3) 8 | 9 | % Method 1: Using row,column numerical indicies 10 | mat(3,2) 11 | 12 | % Method 2: Using linear indexing 13 | mat(6) 14 | 15 | % Method 3: Using logincal indexing with a linear vector 16 | index = logical([0 0 0 0 0 1 0 0 0]) 17 | mat(index) 18 | 19 | % Method 4: Using logical indexing (with a mask matrix) 20 | mask = logical([0 0 0; ... 21 | 0 0 0; ... 22 | 0 1 0]) 23 | mat(mask) 24 | 25 | 26 | 27 | %% Ex. 2: Using logical indexing to reference matrix elements 28 | % =========================================================== 29 | clear 30 | clc 31 | 32 | mat = randn(5); 33 | disp(mat) 34 | 35 | % Assume we need to extract all negative values to 0. 36 | % Let's do this on a copy of the matrix because we want to demo another 37 | % method to do this 38 | mat2 = mat; 39 | 40 | mask = mat2 < 0; % creating a logical indexing matrix which identifies 41 | % negative elements 42 | 43 | mat2(mask) = 0; % set all elements identified by the mask to zero 44 | disp(mat2) 45 | 46 | % Method 2: you can combine the mask creating and element access to one 47 | % statement as follows. Let's do this on the original "mat" 48 | mat(mat<0) = 0; 49 | disp(mat) 50 | 51 | 52 | %% Ex. 3. Set all values greater than 0.5 to 100 53 | clear 54 | clc 55 | 56 | mat = randn(5) 57 | mat(mat > 0.5) = 100 % Uses logical indexing in the l-value 58 | 59 | 60 | %% Ex. 4 Set all values that are outside of -0.5 and 0.5 to 0 61 | clear 62 | clc 63 | 64 | mat = randn(5) 65 | mat(mat<-0.5 | mat>0.5) = 0 % NOTE: we use element-by-element OR " 66 | % operator "|" to create the mask 67 | 68 | 69 | -------------------------------------------------------------------------------- /lec_2_variables_and_numeric_opertors.m: -------------------------------------------------------------------------------- 1 | % This script demonstrates basic operations with variables and 2 | % built-in functions 3 | 4 | 5 | % Initializing a variable with a numeric value 6 | age = 17; 7 | 8 | % Re-assigning another value to the same variable 9 | age = 18; 10 | 11 | 12 | % Incrementing the value of the variable 13 | age = age + 1; 14 | 15 | 16 | % Initializing two other variables 17 | baseDailySalary = 78.50; 18 | todayCommission = 7.75; 19 | 20 | % Evaluating an expression and assigning it's value to another variable 21 | todayPayment = baseDailySalary + todayCommission; 22 | 23 | 24 | % Use of more operators 25 | numWorkers = 12; 26 | 27 | totalLabourCost = numWorkers * todayPayment; % multiplication 28 | 29 | % Another way to do the same calculation 30 | totalLabourCostComputedAnotherWay = numWorkers * (baseDailySalary + todayCommission); 31 | 32 | % Let's list the details of variables that are in the workspace on the 33 | % command window 34 | whos 35 | 36 | 37 | % converting the age to an unsigned 8-bit integer and assigning it to 38 | % another variable 39 | age2 = uint8(age); 40 | 41 | 42 | % Demonstrate effects of te format command 43 | 44 | format short 45 | value = pi % should show value with 4 decimal places 46 | 47 | format long 48 | value = pi % should show value with more decimal places 49 | 50 | format compact 51 | value = pi % should produce less line spacing in the command window 52 | 53 | format loose 54 | value = pi % should produce more line spacing in the command window 55 | 56 | format % this brings back the default behaviour 57 | value = pi 58 | 59 | 60 | % More Numeric Operators 61 | a = 8; 62 | b = 4; 63 | a/b % divided by. The result is 2 64 | a\b % divided into. The result is 0.5 65 | a^2 % Exponent. 66 | -a % Negation. 67 | 68 | 69 | % some basic commands 70 | clear a % deletes the variable a from the workspace 71 | clear % clears all variables from the workspace 72 | clc % clear the command window 73 | exit % closes MATLAB 74 | 75 | 76 | -------------------------------------------------------------------------------- /Lec21/cell_arrays.m: -------------------------------------------------------------------------------- 1 | % 2 | % Cell Arrays 3 | % 4 | % Reference: Attaway, Chapter 8.1 5 | % 6 | % Lecture 21. March 24, 2020 7 | % 8 | 9 | clear 10 | clc 11 | 12 | % Creating a cell array containing different types of elements 13 | cellVec = {12, 'aeiou', 1:100, "Hello World!"} 14 | 15 | cellMat = {12, 'aeiou'; 1:100, "Hello World!"} 16 | 17 | whos 18 | class(cellVec) 19 | class(cellMat) 20 | 21 | 22 | % Accessing elements of a cell array or cell matrix 23 | val1 = cellVec{2} 24 | cellVec{2} = 'Mary had a little lamb' 25 | 26 | val2 = cellMat{1,2} 27 | cellMat{1,2} = 'Mary had a little lamb' 28 | 29 | 30 | % Cell arrays of charactor vectors 31 | cvnames = {'Sue', 'Cathy', 'John'} 32 | 33 | strlength(cvnames) 34 | 35 | % CELLSTR: Converting a string array into a cell array of characters 36 | birds = ["parrot", "crow", "nightingale"] 37 | cellstr(birds) 38 | 39 | % STRJOIN: Joining all strings in a cell array into one string 40 | cellArray = {'2020' '03', '24'} 41 | strjoin(cellArray, '-') 42 | 43 | % STRSPLIT: Splitting a string into a cell array 44 | strsplit('2020-03-24', '-') 45 | strsplit('the quick brown fox jumped over the lazy dog') % default delimiter of white space 46 | 47 | 48 | % ISCELLSTR: Checking if all elements of a cell array are strings 49 | names = {'Mary', 'John', 'Peter'} 50 | iscellstr(names) 51 | 52 | data = {'Amy', 20} 53 | iscellstr(data) 54 | 55 | % CELL: creates empty cell arrays 56 | x1 = cell(1) % creates one-element cell. 57 | x2 = cell(1,3) % creates a 1x3 cell array 58 | x3 = cell (3,1) % creates a 3x1 cell array 59 | x4 = cell(3) % creates a 3x3 cell array 60 | 61 | 62 | % FIELDNAMES: this is a function for listing names of all fields 63 | % in a structure. It results a cell array. 64 | employee = struct('FirstName', 'James', ... 65 | 'LastName', 'Beck', ... 66 | 'Age', 27, ... 67 | 'Street', '123 40 Ave', ... 68 | 'City', 'Edmonton', ... 69 | 'Province', 'AB'); 70 | 71 | fieldnames(employee) -------------------------------------------------------------------------------- /Lec15/function_test.m: -------------------------------------------------------------------------------- 1 | % This script tests various user defined functions 2 | % 3 | % Author: YOUR NAME 4 | % ENCMP100 B3 - Winter 2020. 5 | 6 | 7 | %% Calculating the volume of a cone 8 | 9 | clear 10 | clc 11 | 12 | % Taking radius and height as inputs 13 | r = input('Radius of the cone: '); 14 | h = input('Height of the cone: '); 15 | 16 | % Calculating the volume within this script 17 | if r < 0 18 | error('Radius of a cone must be positive') 19 | end 20 | 21 | volume = (pi/3) * r^2 * h; 22 | fprintf('Volume computed by the script: %.2f\n', volume) 23 | 24 | % Using the user-defined function conevol. 25 | % NOTE: Put a breapoint inside te function and check the workspace/scope 26 | whos 27 | volume2 = conevol(r, h); 28 | fprintf('Volume computed by the user-defined function: %.2f\n', volume2) 29 | 30 | 31 | %% User defined function returning two arguments 32 | % Calculating and returning the circumference and area of a circle 33 | clear 34 | clc 35 | 36 | rad = input('Enter radius: '); 37 | 38 | % using the user-defined class circleinfo 39 | [a, c] = circleinfo(rad); 40 | fprintf('Radius = %.2f\nArea = %.2f\nCircumference = %.2f\n\n', rad, a, c) 41 | 42 | %% Function containing local vaiables 43 | clear 44 | clc 45 | 46 | rad = 2; 47 | h = 5; 48 | 49 | % NOTE: Put a breapoint inside te function and check the workspace/scope 50 | whos 51 | area = cyl_area(rad, h); 52 | fprintf('Radius: %d\nHeight: %d\nSurface area: %.2f\n', rad, h, area) 53 | 54 | %% User-defined functions with no return values. 55 | clear 56 | clc 57 | 58 | print_cumsum(2) 59 | 60 | print_cumsum(-2) 61 | 62 | print_cumsum([2 8]) 63 | 64 | print_cumsum([8 2]) 65 | 66 | print_cumsum([2 8 2]) 67 | 68 | print_cumsum([8 2 2]) 69 | 70 | % The followings should print an error message 71 | print_cumsum([]) 72 | print_cumsum([1 2 3 4]) 73 | print_cumsum([1 2; 3 4]) 74 | 75 | %% Defining a local function which can only be accessed within the script which defines it. 76 | 77 | clear 78 | clc 79 | 80 | rad = 2; 81 | h = 5; 82 | 83 | vol = cyl_vol(rad, h); 84 | fprintf('Radius: %d\nHeight: %d\nVOlume: %.2f\n', rad, h, vol) 85 | 86 | 87 | function v = cyl_vol(radius, height) 88 | 89 | crossSection = pi * radius; 90 | v = crossSection * height; 91 | 92 | end 93 | 94 | -------------------------------------------------------------------------------- /Lec6/lec_6_1_vec_and_mat_as_function_arguments.m: -------------------------------------------------------------------------------- 1 | % Lecture 6 Part 1 - Matrices as function arguments 2 | % Chapter 2.1 and 2.2 Attaway 3 | 4 | clear 5 | clc 6 | 7 | % Changing matrix dimensions 8 | mat = [(1:4)' (5:8)' (9:12)'] 9 | 10 | % RESHAPE: takes values of matA column-by-column and 11 | % reorganizes them into another matrix of given number of 12 | % rows and columns 13 | reshape(mat, 6, 2) 14 | 15 | % FLIPLR: flips left to right 16 | mat 17 | fliplr(mat) 18 | 19 | % FLIPUD: flips upside down 20 | mat 21 | flipud(mat) 22 | 23 | 24 | % ROT90: rotates a matrix 25 | mat 26 | rot90(mat) % 90 degrees counterclockwise 27 | rot90(mat, 2) % 180 degrees counterclockwise 28 | rot90(mat, -1) % 90 degrees clockwise 29 | 30 | 31 | % Creating a large matrix by repeating a smaller one 32 | mat = [1 2; 3 4] 33 | mat2 = repmat(mat, 2) % repeats over 2 rows and 2 columns 34 | mat3 = repmat(mat, 3, 2) % repeats 3 rows and 2 columns 35 | 36 | 37 | 38 | % Matricies and Vectors as Function Arguments 39 | % =========================================== 40 | 41 | % absolute value of all elements 42 | mat = reshape(-5:6, 4, 3) % creating a matrix by reshaping a vector 43 | mat2 = abs(mat) 44 | 45 | 46 | % sign function 47 | vec = -2:2 48 | vec2 = sign(vec) 49 | 50 | 51 | % min / max functions 52 | vec = [5:2:15] 53 | min(vec) % minimum value of the vector 54 | max(vec) % maximum value of the vector 55 | 56 | mat = randi(99, 4, 3) 57 | min(mat) % results a row vector containing min of each column 58 | max(mat) % results a row vector containing max of each column 59 | 60 | 61 | % sum and cumulative sum applies to vectors and matricies 62 | vec = 1:4 63 | sum(vec) % sum of all elements 64 | cumsum(vec) % cumulative sum vector 65 | 66 | 67 | mat = randi(10, 3) 68 | sum(mat) % sum of elemnts in each column 69 | cumsum(mat) % cumulative sum of each column 70 | 71 | % product applies to vectors and matricies 72 | vec 73 | prod(vec) % product of all elements 74 | cumprod(vec) % cumulative product of elements 75 | 76 | 77 | mat 78 | prod(mat) % product of elements in each column 79 | cumprod(mat) % cumulative product of each column 80 | 81 | % difference between adjuscent elements 82 | vec 83 | diff(vec) 84 | 85 | mat 86 | diff(mat) % diff of each column 87 | 88 | 89 | -------------------------------------------------------------------------------- /Lec22/file_io.m: -------------------------------------------------------------------------------- 1 | % 2 | % Low-level file input/output operations 3 | % 4 | % Reference: Attaway Chapter 9.3 5 | % 6 | % Lecture 22. ENCMP100B3 7 | % 8 | 9 | 10 | %% Low-level reading from a file 11 | 12 | clc 13 | 14 | % STEP1: Opening a file for reading. This returns a "file ID" 15 | fileId = fopen('twisters.txt', 'r'); % 'r' represents the read mode 16 | 17 | % STEP2: check whether the file reading was successful 18 | if fileId == -1 19 | error('Failed to open the file for reading') 20 | else 21 | 22 | % STEP 3: Keep reading the file line by line until the end- of-file 23 | % is reached, 24 | while ~feof(fileId) 25 | 26 | % Read next line from the file 27 | line = fgetl(fileId); 28 | 29 | % Do something with the line that was read 30 | disp(line) 31 | 32 | end 33 | 34 | % STEP 4: We are done reading, therefore, close the file 35 | result = fclose(fileId); 36 | 37 | if result ~= 0 38 | error('Failed to close the file') 39 | end 40 | end 41 | 42 | %% Low-level writing to a file 43 | 44 | % let's create some data to be written to a file 45 | names = {'John', 'Elizabeth', 'Kyle', 'Rose'}; 46 | ages = [18, 22, 17, 16]; 47 | 48 | % STEP1: Openning the file for writing 49 | fid = fopen('mydata.txt', 'w'); % 'w' opens the file in "write" mode. 50 | % It overwrites the file if it exists already. 51 | % STEP2: Check whether the file was openned successfully 52 | if fid == -1 53 | error('Failed to open the file for writing') 54 | end 55 | 56 | % STEP3: writing data 57 | for i = 1 : length(names) 58 | fprintf(fid, '%s: %d\n', names{i}, ages(i)); 59 | end 60 | 61 | % STEP 4: We are done writing, therefore, close the file 62 | result = fclose(fid); 63 | 64 | if result ~= 0 65 | error('Failed to close the file') 66 | end 67 | 68 | %% Low-level appending 69 | 70 | mat = reshape(1:9, 3, 3); 71 | 72 | % Opening the file in "append" mode 73 | fid = fopen('mydata.txt', 'a'); 74 | if fid == -1 75 | error('Failed to open the file for appending'); 76 | end 77 | 78 | % Writing data 79 | fprintf(fid, '%d %d %d\n', mat'); 80 | 81 | % Closing the file 82 | if fclose(fid) ~= 0 83 | error('Failed to close the file') 84 | end 85 | 86 | -------------------------------------------------------------------------------- /Lec23/lec23.m: -------------------------------------------------------------------------------- 1 | % Lecture 23 2 | % Command-line debugging techniques and persistent variables 3 | % 4 | 5 | % Command-line debugging 6 | % ====================== 7 | 8 | clear 9 | clc 10 | 11 | % try the following commands on the command line 12 | % and see the effect. 13 | % 14 | % dbstop lec23 15 | % dbstop lec23 32 16 | % dbclear lec23 17 | % dbstop lec23 30 18 | % dbstop lec23 34 19 | % dbstop lec23 44 20 | % 21 | % lec23 22 | % dbstep 23 | % dbstep 24 | % dbstep 25 | % 26 | % dbcont 27 | % dbcont 28 | % dbquit 29 | 30 | rad = 4; 31 | 32 | [a, c] = circleinfo(rad); 33 | 34 | 35 | fprintf('Radius = %.2f\n', rad) 36 | fprintf('Circumference = %.2f\n', c) 37 | fprintf('Area = %.2f\n\n', a) 38 | 39 | disp('Mary had a little lamb') 40 | disp('Row row row your boat') 41 | disp('Old macdonald had a farm') 42 | 43 | for r = rand(1,10) * 20 44 | [a, c] = circleinfo(r); 45 | 46 | fprintf('Radius = %.2f\n', rad) 47 | fprintf('Circumference = %.2f\n', c) 48 | fprintf('Area = %.2f\n\n', a) 49 | end 50 | fprintf('Good bye ...\n') 51 | 52 | %% Command-line Debugging in Practice 53 | % 54 | % Let's clear all debug points and try few things that are 55 | % more applicable to the real world. When we run this code, 56 | % we will get some errors inside the circileinfo file. I 57 | % will show you how to use the error information to put 58 | % appropriate breakpoints inside the file and debug the code 59 | % during the class. 60 | 61 | % Let's clear all breakpoints and run this file again by 62 | % typing the following commands in the command prompt 63 | % 64 | % dbclear lec23 65 | % lec23 66 | % 67 | 68 | clear 69 | clc 70 | 71 | r = rand(2,4) * 20; 72 | [a, c] = circleinfo(r); 73 | 74 | disp('Radius') 75 | disp(r) 76 | 77 | disp('Area') 78 | disp(a) 79 | 80 | disp('Circumference') 81 | disp(c) 82 | 83 | 84 | %% Persistent Variables 85 | % ==================== 86 | 87 | % Let's review the function in aggregate.m and fix it to 88 | % make sure it works in the way it's documentation 89 | % describes. 90 | 91 | clear 92 | 93 | 94 | vals = randi(10, 1, 10); 95 | disp(vals) 96 | for i = 1 : length(vals) 97 | result = aggregate(vals(i)); 98 | fprintf('Result: %d\n', result) 99 | end 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /Lec23/in-class-work/lec23.m: -------------------------------------------------------------------------------- 1 | % Lecture 23 2 | % Command-line debugging techniques and persistent variables 3 | % 4 | 5 | % Command-line debugging 6 | % ====================== 7 | 8 | clear 9 | clc 10 | 11 | % try the following commands on the command line 12 | % and see the effect. 13 | % 14 | % dbstop lec23 15 | % dbstop lec23 32 16 | % dbclear lec23 17 | % dbstop lec23 30 18 | % dbstop lec23 34 19 | % dbstop lec23 44 20 | % 21 | % lec23 22 | % dbstep 23 | % dbstep 24 | % dbstep 25 | % 26 | % dbcont 27 | % dbcont 28 | % dbquit 29 | 30 | rad = 4; 31 | 32 | [a, c] = circleinfo(rad); 33 | 34 | 35 | fprintf('Radius = %.2f\n', rad) 36 | fprintf('Circumference = %.2f\n', c) 37 | fprintf('Area = %.2f\n\n', a) 38 | 39 | disp('Mary had a little lamb') 40 | disp('Row row row your boat') 41 | disp('Old macdonald had a farm') 42 | 43 | for r = rand(1,10) * 20 44 | [a, c] = circleinfo(r); 45 | 46 | fprintf('Radius = %.2f\n', rad) 47 | fprintf('Circumference = %.2f\n', c) 48 | fprintf('Area = %.2f\n\n', a) 49 | end 50 | fprintf('Good bye ...\n') 51 | 52 | %% Command-line Debugging in Practice 53 | % 54 | % Let's clear all debug points and try few things that are 55 | % more applicable to the real world. When we run this code, 56 | % we will get some errors inside the circileinfo file. I 57 | % will show you how to use the error information to put 58 | % appropriate breakpoints inside the file and debug the code 59 | % during the class. 60 | 61 | % Let's clear all breakpoints and run this file again by 62 | % typing the following commands in the command prompt 63 | % 64 | % dbclear lec23 65 | % lec23 66 | % 67 | 68 | clear 69 | clc 70 | 71 | r = rand(2,4) * 20; 72 | [a, c] = circleinfo(r); 73 | 74 | disp('Radius') 75 | disp(r) 76 | 77 | disp('Area') 78 | disp(a) 79 | 80 | disp('Circumference') 81 | disp(c) 82 | 83 | 84 | %% Persistent Variables 85 | % ==================== 86 | 87 | % Let's review the function in aggregate.m and fix it to 88 | % make sure it works in the way it's documentation 89 | % describes. 90 | 91 | clear all 92 | clc 93 | 94 | vals = randi(10, 1, 10); 95 | disp(vals) 96 | for i = 1 : length(vals) 97 | result = aggregate(vals(i)); 98 | fprintf('Result: %d\n', result) 99 | end 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /Lec10/in-class-work/lec_10_2.m: -------------------------------------------------------------------------------- 1 | % Lecture 10 Part 2: FOR and WHILE loops 2 | % Chapter 5.1, 5.2, 5.3 3 | 4 | %% FOR loop (iterating through a fixed number of times 5 | clc 6 | for i = 1:2:5 7 | fprintf('%d: Hello world\n', i); 8 | 9 | end 10 | 11 | %% FOR loop ex. #2 12 | clc 13 | vec = randi(99, 1, 5) 14 | for i = vec 15 | fprintf('%d: Hello world\n', i); 16 | end 17 | 18 | %% FOR loop ex. #3 19 | % Inputting a vector of values one by one 20 | clc 21 | clear 22 | vec = zeros(1, 5); % pre-allocate storage 23 | for i = 1:5 24 | vec(i) = input('Enter a number: '); 25 | end 26 | disp('You entered:') 27 | disp(vec) 28 | 29 | %% EXERCISE: Create version 3 of "circleinfo.m" which would perform the 30 | % computation for 5 times. 31 | 32 | 33 | 34 | %% Nested FOR loops 35 | clear 36 | clc 37 | 38 | for a = 1:5 39 | for b = 1:3 40 | fprintf('a=%d, b=%d: Hello world\n', a, b) 41 | end 42 | fprintf('\n') 43 | end 44 | 45 | 46 | %% Printing a triangle of stars 47 | clear 48 | clc 49 | 50 | rows = input('Enter number of rows: '); 51 | for i=1:rows 52 | % inner loop just iterates to the value of i 53 | for j=1:i 54 | fprintf('* ') 55 | end 56 | fprintf('\n') 57 | end 58 | 59 | 60 | %% 61 | % Using SIZE function to get the rows and columns 62 | % of a matrix and then iterating through 63 | % all rows and and all columns, row by row 64 | 65 | clear 66 | clc 67 | 68 | mat = randi([10, 99], 4, 5); 69 | disp(mat) 70 | 71 | [rows, cols] = size(mat); % SIZE function returns the 72 | % number of rows and columns 73 | for r = 1:rows 74 | for c = 1:cols 75 | val = mat(r,c); 76 | if val < 50 77 | fprintf('%6c', '.') 78 | else 79 | fprintf('%6c', '*') 80 | end 81 | end 82 | fprintf('\n') 83 | end 84 | 85 | %% WHILE loop 86 | 87 | clc 88 | 89 | % Radius of the circle 90 | radius = input ('Enter radius: '); 91 | 92 | while radius > 0 93 | 94 | % Calculating the circumference 95 | circ = 2 * pi * radius; 96 | 97 | % Calculating the area 98 | area = pi * radius^2; 99 | 100 | % Display the result 101 | fprintf('Radius: %.2f\nCircumference: %.2f\nArea: %.2f\n', ... 102 | radius, circ, area) 103 | 104 | fprintf('\n') 105 | radius = input ('Enter radius: '); 106 | end 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /Lec7/lec_7_input_output.m: -------------------------------------------------------------------------------- 1 | % Lecture 6 Inputs and Outputs 2 | % Chapter 3.3 Attaway 3 | 4 | 5 | 6 | % Inputting scalars and printing them 7 | % =================================== 8 | val = input('Enter a numeric value: '); 9 | 10 | % Using disp to print just the value of the variable val 11 | disp(val) 12 | 13 | % Using fprintf to print the value in various forms 14 | fprintf('%d\n', val) % print just the value in interger format and go to next line 15 | fprintf('Value in integer format:%d\n', val) 16 | fprintf('Value in floating point format with default number of decimal places:%f\n', val) 17 | fprintf('Floating point with 2 decimal places:%.2f\n', val) 18 | fprintf('Float with 2 decimal places:%8.2f(printed in a field of 8 characters, right aligned)\n', val) 19 | fprintf('Float with 2 decimal places:%-8.2f(printed in a field of 8 characters, left aligned)\n', val) 20 | 21 | % Inputting character-arrays (i.e. a string of characters) and displaying them 22 | % ============================================================================ 23 | val = input('Enter any text: ', 's'); 24 | 25 | % Using disp to display just the value 26 | disp(val) 27 | 28 | % Using fprintf to display the value as a character-array 29 | % (a.k.a string of characters) in various forms 30 | fprintf('%s\n', val); % just display the value and a new-line character 31 | fprintf('You entered:%s\n', va) 32 | fprintf('You entered:%10s(printd in a field of 10 characters, right aligned)\n', val) 33 | fprintf('You entered:%-10s(printd in a field of 10 characters, left aligned)\n', val) 34 | 35 | 36 | % Printing vectors 37 | % ================ 38 | vec = 1:5; 39 | disp(vec) % printing just the value 40 | 41 | fprintf('%d ', vec) % prints all elements in one line 42 | fprintf('%d\n', vec) % print all elements, each in a new line 43 | 44 | fprintf('%d %d\n', vec) 45 | 46 | % Printing matricies 47 | % ================== 48 | mat = reshape(1:12, 3, 4)'; % Creting a matrix by reshaping a vector and transposing it 49 | 50 | disp(mat) % Printing just the value 51 | 52 | fprintf('%d ', mat) % takes elements column by column and prints in one line 53 | 54 | fprintf('%d \n', mat) % takes elements column by column and prints value one per line 55 | 56 | fprintf('%d %d\n', mat) % takes elements column by column and prints two per line 57 | 58 | fprintf('%d %d %d\n', mat) % takes elements column by column and prints two per line 59 | 60 | % NOTE: To print values row by row, we should pass the transpose to fprintf 61 | fprintf('%d %d %d\n', mat') 62 | 63 | % let's change the above to display each value in a width of 2 characters 64 | fprintf('%2d %2d %2d\n', mat') 65 | 66 | 67 | -------------------------------------------------------------------------------- /Lec9/lec_9_if_statement.m: -------------------------------------------------------------------------------- 1 | % Lecture 9: Selection Statements 2 | % Chapter 4.1 to 4.4 3 | 4 | 5 | % IF statement 6 | num = rand 7 | 8 | if num < 0.5 9 | disp('The number is smaller than 0.5') 10 | end 11 | 12 | 13 | % IF/ELSE statement 14 | num = rand; 15 | 16 | if num < 0.5 17 | fprintf('The number %.2f is smaller than 0.5\n', num) 18 | else 19 | fprintf('The number %.2f is greater than or equal to 0.5\n', num) 20 | end 21 | 22 | % EXERCISE: Create version 2 of "circleinfo.m" which would produce an 23 | % error if a negative radius value is entered 24 | 25 | 26 | 27 | % Nested IF/ELSE statements 28 | % CHECK OUT the "salesstatus.m" example script. 29 | 30 | 31 | % Nested IF/ELSE statements that can be merged into 32 | % a more compact IF/ELSEIF/ELSE statements. 33 | 34 | num = 0.6; %rand; 35 | 36 | if num < 0.5 37 | fprintf('A: The number %.2f is smaller than 0.5\n', num) 38 | else 39 | if num < 0.75 40 | fprintf('B: The number %.2f is greater than or equal to 0.5 but less than 0.75\n', num) 41 | else 42 | fprintf('C: The number %.2f is greater than or equal to 0.75\n', num) 43 | end 44 | end 45 | 46 | % IF/ELSEIF/ELSE version 47 | if num < 0.5 48 | fprintf('A: The number %.2f is smaller than 0.5\n', num) 49 | elseif num < 0.75 50 | fprintf('B: The number %.2f is greater than or equal to 0.5 but less than 0.75\n', num) 51 | else 52 | fprintf('C: The number %.2f is greater than or equal to 0.75\n', num) 53 | end 54 | 55 | 56 | % A loooooong IF/ELSEIF/ELSE statements with all conditions testing EQUALITY 57 | clc 58 | day = input('Enter the day number (Monday = 1, etc): '); 59 | if day == 1 60 | disp('It''s Monday') 61 | elseif day == 2 62 | disp('Yay! it''s ENCMP100 day') 63 | elseif day == 3 64 | disp('It''s Wednesday') 65 | elseif day == 4 66 | disp('Yay! it''s ENCMP100 day') 67 | else 68 | disp('Can''t wait until next Tuesday') 69 | end 70 | 71 | 72 | % SWITCH/CASE statement: a better alternative 73 | day = input('Enter the day number (Monday = 1, etc): '); 74 | switch day 75 | case 1 76 | disp('It''s Monday') 77 | case 2 78 | disp('Yay! it''s ENCMP100 day') 79 | case 3 80 | disp('It''s Wednesday') 81 | case 4 82 | disp('Yay! it''s ENCMP100 day') 83 | otherwise 84 | disp('Can''t wait until next Tuesday') 85 | end 86 | 87 | % Even more compact version ... 88 | day = input('Enter the day number (Monday = 1, etc): '); 89 | switch day 90 | case 1 91 | disp('It''s Monday') 92 | case {2, 4} 93 | disp('Yay! it''s ENCMP100 day') 94 | case 3 95 | disp('It''s Wednesday') 96 | otherwise 97 | disp('Can''t wait until next Tuesday') 98 | end 99 | -------------------------------------------------------------------------------- /Lec4/lec_4_1_characters_strings_and_variable_types.m: -------------------------------------------------------------------------------- 1 | % Lecture 4 Part 1, Characters, Strings, and Variable Types 2 | % Chapter 1.5 and 1.7, Attaway 3 | 4 | 5 | % Characters, Chararacter Arrays, and String Objects 6 | % ================================================== 7 | 8 | 9 | % Defining a single character and assigning it to a variable 10 | char1 = 'x' 11 | char2 = 'k' 12 | char3 = '4' % This is the character 4, NOT the number 4. 13 | num = 4 % This is the number 4 14 | 15 | whos 16 | 17 | % Defining an array (or vector) of characters 18 | myCharArray1 = 'Hello World!' 19 | 20 | % We can also define the above character arrays literally as an array of 21 | % characters as follows. 22 | myCharArray2 = ['H','e','l','l','o',' ','W','o','r','l','d','!'] 23 | 24 | % You can use the "length" function to find the length of a character array 25 | numChars1 = length(myCharArray1) 26 | numChars2 = length(myCharArray2) 27 | 28 | whos 29 | 30 | % With recent versions of MATLAB, you can define array of characters as a 31 | % special type of "string" objects. Note that strings are internaly 32 | % represented differently than character arrays. 33 | myString1 = "Hello World!" % Note that we use double quotes to define strings 34 | % We use single quotes to define character 35 | % arrays. 36 | 37 | 38 | 39 | % Types (or classes) 40 | % ================== 41 | 42 | % Let's clear the work space and the command window. 43 | clear 44 | clc 45 | 46 | 47 | % Let's assign several numeric, character, character-array and strnig 48 | % values to some variables 49 | myNum = 10 50 | myChar = 'A' 51 | myCharArray = 'ENCMP100 is Awesome' 52 | myString = "ENCMP100 is Awesome" 53 | 54 | whos 55 | 56 | 57 | % You can use the built-in function "class" to find the class or type of a 58 | % variable programatically. The "class" function returns the variabe type 59 | % as a string. 60 | class(myNum) 61 | 62 | class(myChar) 63 | 64 | class(myCharArray) 65 | 66 | class(myString) 67 | 68 | 69 | 70 | % Type Casting 71 | % ============ 72 | 73 | % We can use the built-in function "double" to convert a character value 74 | % into a numeric value 75 | 76 | 77 | num1 = double('A') 78 | 79 | num2 = double('B') 80 | 81 | num3 = double('a') 82 | 83 | num4 = double('b') 84 | 85 | 86 | numVec1 = double('hello') 87 | 88 | 89 | % We can use the built-in function "char" to convert a numeric value 90 | % into a character value 91 | 92 | char1 = char(65) 93 | 94 | char2 = char(99) 95 | 96 | charArray = char([104 101 108 108 111]) 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /Lec16/structures.m: -------------------------------------------------------------------------------- 1 | % Structures 2 | % Chapter 8.2 3 | 4 | clear 5 | clc 6 | 7 | % Creating a structure with different fields to store 8 | % data of a person 9 | employee = struct('FirstName', 'James', ... 10 | 'LastName', 'Beck', ... 11 | 'Age', 27, ... 12 | 'Street', '123 40 Ave', ... 13 | 'City', 'Edmonton', ... 14 | 'Province', 'AB'); 15 | 16 | 17 | employee2 = struct('FirstName', 'John', ... 18 | 'LastName', 'Boyd', ... 19 | 'Age', 72, ... 20 | 'Street', '454 40 Ave', ... 21 | 'City', 'Calgary', ... 22 | 'Province', 'AB'); 23 | 24 | whos 25 | 26 | % Displaying the whole structure 27 | disp(employee) 28 | 29 | % Accessing/displaying only one field in 30 | % the structure using the dot operator 31 | disp(employee.LastName) 32 | 33 | % Modifying a particular field 34 | employee.Age = 32; 35 | disp(employee) 36 | 37 | % Adding a new field using the dot operator. 38 | % This, however, is not very efficient because 39 | % it "grows" the structure. 40 | employee.Country = 'Canada'; 41 | disp(employee) 42 | 43 | % Removing a field from the structure 44 | empl = rmfield(employee, 'Age'); 45 | 46 | % Displaying the original structure passed on to remfield 47 | % Note that the "Age" field has not been removed from it. 48 | disp(employee) 49 | 50 | 51 | % Displaying the result returned by rmfield. 52 | % Note that it has no "Age" field. 53 | disp(empl) 54 | 55 | % To remove the field and update the original, we should 56 | % assign the result of rmfield to the . 57 | employee = rmfield(employee, 'Age'); 58 | 59 | %% Structure-related functions 60 | 61 | % ISFILED - check whether a given field exists in a structure. 62 | isfield(employee, 'FirstName') 63 | isfield(employee, 'Salary') 64 | 65 | % FIELDNAMES - returns all names of fields. This returns a "cell array" 66 | fieldnames(employee) 67 | 68 | % ISSTRUCT - checks whether a variable is a structure 69 | isstruct(employee) 70 | 71 | mat = rand(2); 72 | isstruct(mat) 73 | 74 | %% Preallocation 75 | 76 | clear 77 | clc 78 | 79 | person = struct('First_Name', '', ... 80 | 'Last_Name', '', ... 81 | 'Address', '', ... 82 | 'Salary', [], ... 83 | 'Age', 0); 84 | 85 | 86 | % preallocating a 100 element array of person structures 87 | personArray = repmat(person, 1, 100); 88 | 89 | for i = 1:100 90 | personArray(i).First_Name = input('Firt Name: ', 's'); 91 | personArray(i).Last_Name = input('Last Name: ', 's'); 92 | personArray(i).Age = input('Age: '); 93 | end 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /Lec5/lec_5_2_matrices.m: -------------------------------------------------------------------------------- 1 | % Lecture 5 Part 2, Matrices 2 | % Chapter 2.1 Attaway 3 | 4 | clear 5 | clc 6 | 7 | % Creating Matrices 8 | % ================= 9 | 10 | % Defining a 2x3 matrix; use a new line for the second row 11 | mat1 = [1 2 3 12 | 4 5 6] 13 | 14 | % we can also use a semicolon to separate rows 15 | mat2 = [1 2 3; 4 5 6] 16 | 17 | 18 | % using built-in functions 19 | mat3 = ones(4) % Creates a 4x4 matrix of 1s 20 | mat4 = ones(4,2) % Creares a 4x2 matrix of 1s 21 | 22 | mat5 = zeros(4) % Creates a 4x4 matrix of 0s 23 | mat6 = zeros(4,2) % Creares a 4x2 matrix of 0s 24 | 25 | 26 | % using rand to create matrices of uniformly distributed 27 | % random numbers from 0 to 1 28 | mat7 = rand(3) % 3x3 29 | mat8 = rand(3,2) % 3x2 30 | 31 | % using randn to create matrices of normally distributed 32 | % random numbers 33 | mat9 = randn(3) % 3x3 34 | mat10 = randn(3,2) % 3x2 35 | 36 | % using randi to create matries of random integers 37 | % note: the first vector argument specifies the min and max values 38 | mat11 = randi([5 50], 3) % 3x3 39 | mat12 = randi([5 50], 3, 2) % 3x2 40 | 41 | 42 | % Referring to and Modifying Matrix Elements 43 | % ========================================== 44 | 45 | clear 46 | clc 47 | 48 | mat = rand(3) % 3x3 random matrix 49 | 50 | % Using "subscripted indexing" i.e. by using row,col indicies 51 | mat(2,3) % get value of element at 2nd row, 3rd column 52 | mat(2,3) = 10 % modify the value 53 | 54 | % Accsing an entire column using : operator 55 | mat = randi([1 100], 5) 56 | mat(:, 2) % 2nd column 57 | mat(:, 3) % 3rd column 58 | mat(:, end) % last column 59 | 60 | 61 | % Accsing an entire row using : operator 62 | mat = randi([1 50], 5) 63 | mat(2, :) % 2nd row 64 | mat(3, :) % 3rd row 65 | mat(end, :) % last row 66 | 67 | % Accessing a subset of a matrix 68 | mat = randi([1 50], 5) 69 | mat(2:4, 1:3) % rows 2 to 4 and columns 1 to 3 70 | 71 | % Modifying a subset of a matrix by assigning a scalar 72 | % to all elements 73 | mat(2:4, 1:3) = -1 74 | 75 | % Modifying a subset of a matrix by assigning 76 | % another matrix with same dimensions as the subset 77 | mat(2:3, 4:5) = [88 88; 99 99] 78 | 79 | % Using "liner indexing" to access an element 80 | mat = randi([1 50], 5) 81 | mat(12) 82 | 83 | % Dimensions and size of a matrix 84 | mat = randi([1 50], 5, 4) 85 | size(mat) 86 | [r, c] = size(mat) 87 | length(mat) % returns the largest dimension 88 | numel(mat) % returns the number of elements 89 | 90 | 91 | % Using empty vectors to remove a row or a column 92 | mat(:,2) = [] % deletes the 2nd column 93 | mat(2:4, :) = [] % deletes rows 2, 3 and 4 94 | 95 | 96 | % Adding an entire row or a column to a matrix 97 | % This is NOT good practice as it is a slow operation 98 | mat = randi([1 50], 3) 99 | mat(6,:) = 99 % Add a row of the same scalars 100 | 101 | mat(:,4) = [1 2 3 4 5 6]' % Add a column vector 102 | -------------------------------------------------------------------------------- /lec_3_1.m: -------------------------------------------------------------------------------- 1 | % Lecture 3 Part 1, Expressions and Built-in Functions 2 | % Chapters 1.4 and 1.8 Attaway 3 | 4 | % This script demonstrates the use of 5 | % (a) expressions, opertors and precedence 6 | % (b) built-in constants, and 7 | % (c) built-in funcions 8 | 9 | 10 | % (a) Expressions, Operators and Precedence 11 | % ========================================= 12 | 13 | 14 | 4 + 5 % Addition 15 | 16 | 4 - 5 % Subtraction 17 | 18 | -5 % Negation 19 | 20 | 4 * 5 % Multiplication 21 | 22 | 8 / 4 % Division (divided by) 23 | 24 | 8 \ 4 % Division (divided into) 25 | 26 | 3^2 % Exponent 27 | 28 | % Operator precedence examples 29 | 4 + 5 * 3 30 | 31 | (4 + 5) * 3 32 | 33 | 2*3^2 34 | 35 | (2*3)^2 36 | 37 | -5^2 38 | 39 | (-5)^2 40 | 41 | 5 * 4 / 2 * 3 42 | 43 | 44 | 45 | % (b) Built-in Constants 46 | % ====================== 47 | 48 | % buil-in constants 49 | pi 50 | 51 | Inf % infinity 52 | 1.5/0 53 | 54 | NaN % Not a Number 55 | 0/0 56 | Inf/Inf 57 | 0 * Inf 58 | 59 | 60 | 61 | % (c) Built-in Functions 62 | % ====================== 63 | 64 | % list all built-in elementary functions 65 | help elfun 66 | 67 | 68 | % Absolute value 69 | abs(-5) % Takes -5 as the "argument" 70 | % and "returns" its magnitude 71 | abs(5) 72 | 73 | 74 | % sine of an angle 75 | sin(pi/6) % argument is in radians 76 | sind(30) % argument is in degrees. 77 | % Note pi/6 radians = 30 degrees 78 | 79 | % sine inverse (arc sine) 80 | asin(0.5) % the return is equal to pi/6 81 | asind(0.5) % the return is 30 degrees 82 | 83 | 84 | % tan of an angle 85 | tan(pi/6) 86 | tand(30) 87 | 88 | % tan inverse 89 | atan(0.5774) 90 | atand(0.5774) 91 | 92 | 93 | % Random Numbers (Pseudorandom numbers) 94 | % ------------------------------------- 95 | 96 | rand % generates a uniformly disreibuted 97 | % random number between 0 and 1 98 | 99 | rand 100 | 101 | rand 102 | 103 | 104 | rng('shuffle') % sets a clock-based seed for the 105 | % random number generator 106 | 107 | rand 108 | rand 109 | 110 | 111 | rng('default') % restores the default seed which 112 | % is used when MATLAB is started 113 | 114 | rand 115 | rand 116 | 117 | 118 | % Saving the current state of the random number 119 | % generator and restoring it later 120 | 121 | myState = rng % saving the state in a variable 122 | 123 | rand % generating some random numbers 124 | rand 125 | rand 126 | 127 | rng(myState) % restoring the saved state 128 | 129 | rand % re-generating the same sequence of random numbers 130 | rand 131 | rand 132 | 133 | 134 | % Random numbers from a normal distribution 135 | randn 136 | randn 137 | randn 138 | 139 | % Random integers from a given range 140 | randi(20) % a random integer from 1 to 20 141 | randi(20) 142 | randi(20) 143 | 144 | 145 | randi([5, 20]) % a random integer from 5 to 20, inclusive 146 | randi([5, 20]) 147 | randi([5, 20]) 148 | -------------------------------------------------------------------------------- /Lec9/in-class-work/lec_9_if_statement.m: -------------------------------------------------------------------------------- 1 | % Lecture 9: Selection Statements 2 | % Chapter 4.1 to 4.4 3 | 4 | 5 | %% IF statement 6 | num = 0.8 %rand 7 | 8 | if num < 0.5 9 | disp('The number is smaller than 0.5') 10 | y = 2 * num; 11 | 12 | end 13 | 14 | 15 | %% IF/ELSE statement 16 | num = 0.9 % rand; 17 | 18 | if num < 0.5 19 | fprintf('The number %.2f is smaller than 0.5\n', num) 20 | t = 5; 21 | else 22 | fprintf('The number %.2f is greater than or equal to 0.5\n', num) 23 | end 24 | 25 | % EXERCISE: Create version 2 of "circleinfo.m" which would produce an 26 | % error if a negative radius value is entered 27 | 28 | 29 | 30 | % Nested IF/ELSE statements 31 | % CHECK OUT the "salesstatus.m" example script. 32 | 33 | 34 | %% Nested IF/ELSE statements that can be merged into 35 | % a more compact IF/ELSEIF/ELSE statements. 36 | 37 | num = 0.6; %rand; 38 | 39 | if num < 0.5 40 | fprintf('A: The number %.2f is smaller than 0.5\n', num) 41 | else 42 | if num < 0.75 43 | fprintf('B: The number %.2f is greater than or equal to 0.5 but less than 0.75\n', num) 44 | else 45 | fprintf('C: The number %.2f is greater than or equal to 0.75\n', num) 46 | end 47 | end 48 | 49 | % IF/ELSEIF/ELSE version 50 | if num < 0.5 51 | fprintf('A: The number %.2f is smaller than 0.5\n', num) 52 | elseif num < 0.75 53 | fprintf('B: The number %.2f is greater than or equal to 0.5 but less than 0.75\n', num) 54 | elseif num < 0.4 55 | disp('Hello, this will never be displayed :(') 56 | else 57 | fprintf('C: The number %.2f is greater than or equal to 0.75\n', num) 58 | end 59 | 60 | 61 | %% A loooooong IF/ELSEIF/ELSE statements with all conditions testing EQUALITY 62 | clc 63 | day = input('Enter the day number (Monday = 1, etc): '); 64 | if day == 1 65 | disp('It''s Monday') 66 | elseif day == 2 67 | disp('Yay! it''s ENCMP100 day') 68 | elseif day == 3 69 | disp('It''s Wednesday') 70 | elseif day == 4 71 | disp('Yay! it''s ENCMP100 day') 72 | else 73 | disp('Can''t wait until next Tuesday') 74 | end 75 | 76 | 77 | %% SWITCH/CASE statement: a better alternative 78 | day = input('Enter the day number (Monday = 1, etc): '); 79 | switch day 80 | case 1 81 | disp('It''s Monday') 82 | y = 25; 83 | case 2 84 | disp('Yay! it''s ENCMP100 day') 85 | case 3 86 | disp('It''s Wednesday') 87 | case 4 88 | disp('Yay! it''s ENCMP100 day') 89 | otherwise 90 | disp('Can''t wait until next Tuesday') 91 | end 92 | 93 | %% Even more compact version ... 94 | day = input('Enter the day number (Monday = 1, etc): '); 95 | switch day 96 | case 1 97 | disp('It''s Monday') 98 | case {2, 4} 99 | disp('Yay! it''s ENCMP100 day') 100 | case 3 101 | disp('It''s Wednesday') 102 | case {5, 6, 7} 103 | disp('Can''t wait until next Tuesday') 104 | otherwise 105 | disp('Are you really from Earth??') 106 | 107 | 108 | end 109 | -------------------------------------------------------------------------------- /Gorillas/v3/shoot.m: -------------------------------------------------------------------------------- 1 | function isWon = shoot(stage, shooter, target, angle, velocity) 2 | % SHOOT calculates the trajectory of the banana thrown by the specified 3 | % activePlayer and displays it in slow motion. For the player #1, this 4 | % function throws the banana in the east direction and for the player #1 it 5 | % throws it in the west direction. The trajectory ends when the banana hits 6 | % on a building (or when it goes beyond the buildings). The function 7 | % returns the index of the building being hit by the banana (or empty if 8 | % the banana does not hit on any building. 9 | 10 | 11 | % Computing the trajectory 12 | x0 = shooter.x; 13 | y0 = shooter.y; 14 | 15 | % Finding the domain (x values) depending on which player is playing 16 | if shooter.Id == 1 17 | x = x0 : max(stage.x) + stage.buildingWidth/2; 18 | else 19 | x = x0 : -1 : 0; 20 | end 21 | 22 | % Calculating the full trajectory y values without limiting it to the first 23 | % building being hit 24 | a = angle; 25 | u = velocity; 26 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 27 | 28 | % Limiting the trajectory to the first hit of the building, if any 29 | [hitIndex, x, y] = findHitBuildingId(stage, shooter, x, y); 30 | 31 | isWon = ~isempty(hitIndex) && ... 32 | hitIndex == target.buildingId && ... 33 | stage.x(hitIndex) - stage.buildingWidth/2 < x(end) && ... 34 | stage.x(hitIndex) + stage.buildingWidth/2 > x(end); 35 | 36 | figure(gcf) % bring the current figure to focus 37 | comet(x, y) 38 | 39 | end 40 | 41 | 42 | 43 | function [hitIndex, trajX, trajY] = findHitBuildingId(stage, player, x, y) 44 | 45 | hitIndex = []; 46 | 47 | if x(1) < x(end) 48 | % throwing towards the west direction 49 | i = player.buildingId; 50 | 51 | while i <= length(stage.x) && isempty(hitIndex) 52 | 53 | entranceWallFaceX = stage.x(i) - stage.buildingWidth/2; 54 | exitWallFaceX = stage.x(i) + stage.buildingWidth/2; 55 | 56 | mask = x >= entranceWallFaceX & ... 57 | x <= exitWallFaceX & ... 58 | y <= stage.y(i); 59 | 60 | mask = find(mask); 61 | 62 | if ~isempty(mask) 63 | hitIndex = i; 64 | trajX = x(1:mask(1)); 65 | trajY = y(1:mask(1)); 66 | end 67 | i = i + 1; 68 | end 69 | else 70 | % throwing towards the east direction 71 | i = player.buildingId; 72 | while i > 0 && isempty(hitIndex) 73 | 74 | entranceWallFaceX = stage.x(i) + stage.buildingWidth/2; 75 | exitWallFaceX = stage.x(i) - stage.buildingWidth/2; 76 | 77 | mask = x <= entranceWallFaceX & ... 78 | x >= exitWallFaceX & ... 79 | y <= stage.y(i); 80 | 81 | mask = find(mask); 82 | 83 | if ~isempty(mask) 84 | hitIndex = i; 85 | trajX = x(1:mask(1)); 86 | trajY = y(1:mask(1)); 87 | end 88 | i = i - 1; 89 | end 90 | end 91 | 92 | if isempty(hitIndex) 93 | trajX = x; 94 | trajY = y; 95 | end 96 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3/shoot.m: -------------------------------------------------------------------------------- 1 | function isWon = shoot(stage, shooter, target, angle, velocity) 2 | % SHOOT calculates the trajectory of the banana thrown by the specified 3 | % activePlayer and displays it in slow motion. For the player #1, this 4 | % function throws the banana in the east direction and for the player #1 it 5 | % throws it in the west direction. The trajectory ends when the banana hits 6 | % on a building (or when it goes beyond the buildings). The function 7 | % returns the index of the building being hit by the banana (or empty if 8 | % the banana does not hit on any building. 9 | 10 | 11 | % Computing the trajectory 12 | x0 = shooter.x; 13 | y0 = shooter.y; 14 | 15 | % Finding the domain (x values) depending on which player is playing 16 | if shooter.Id == 1 17 | x = x0 : max(stage.x) + stage.buildingWidth/2; 18 | else 19 | x = x0 : -1 : 0; 20 | end 21 | 22 | % Calculating the full trajectory y values without limiting it to the first 23 | % building being hit 24 | a = angle; 25 | u = velocity; 26 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 27 | 28 | % Limiting the trajectory to the first hit of the building, if any 29 | [hitIndex, x, y] = findHitBuildingId(stage, shooter, x, y); 30 | 31 | isWon = ~isempty(hitIndex) && ... 32 | hitIndex == target.buildingId && ... 33 | stage.x(hitIndex) - stage.buildingWidth/2 < x(end) && ... 34 | stage.x(hitIndex) + stage.buildingWidth/2 > x(end); 35 | 36 | figure(gcf) % bring the current figure to focus 37 | comet(x, y) 38 | 39 | end 40 | 41 | 42 | 43 | function [hitIndex, trajX, trajY] = findHitBuildingId(stage, player, x, y) 44 | 45 | hitIndex = []; 46 | 47 | if x(1) < x(end) 48 | % throwing towards the west direction 49 | i = player.buildingId; 50 | 51 | while i <= length(stage.x) && isempty(hitIndex) 52 | 53 | entranceWallFaceX = stage.x(i) - stage.buildingWidth/2; 54 | exitWallFaceX = stage.x(i) + stage.buildingWidth/2; 55 | 56 | mask = x >= entranceWallFaceX & ... 57 | x <= exitWallFaceX & ... 58 | y <= stage.y(i); 59 | 60 | mask = find(mask); 61 | 62 | if ~isempty(mask) 63 | hitIndex = i; 64 | trajX = x(1:mask(1)); 65 | trajY = y(1:mask(1)); 66 | end 67 | i = i + 1; 68 | end 69 | else 70 | % throwing towards the east direction 71 | i = player.buildingId; 72 | while i > 0 && isempty(hitIndex) 73 | 74 | entranceWallFaceX = stage.x(i) + stage.buildingWidth/2; 75 | exitWallFaceX = stage.x(i) - stage.buildingWidth/2; 76 | 77 | mask = x <= entranceWallFaceX & ... 78 | x >= exitWallFaceX & ... 79 | y <= stage.y(i); 80 | 81 | mask = find(mask); 82 | 83 | if ~isempty(mask) 84 | hitIndex = i; 85 | trajX = x(1:mask(1)); 86 | trajY = y(1:mask(1)); 87 | end 88 | i = i - 1; 89 | end 90 | end 91 | 92 | if isempty(hitIndex) 93 | trajX = x; 94 | trajY = y; 95 | end 96 | end -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/shoot.m: -------------------------------------------------------------------------------- 1 | function isWon = shoot(stage, shooter, target, angle, velocity) 2 | % SHOOT calculates the trajectory of the banana thrown by the specified 3 | % activePlayer and displays it in slow motion. For the player #1, this 4 | % function throws the banana in the east direction and for the player #1 it 5 | % throws it in the west direction. The trajectory ends when the banana hits 6 | % on a building (or when it goes beyond the buildings). The function 7 | % returns the index of the building being hit by the banana (or empty if 8 | % the banana does not hit on any building. 9 | 10 | 11 | % Computing the trajectory 12 | x0 = shooter.x; 13 | y0 = shooter.y; 14 | 15 | % Finding the domain (x values) depending on which player is playing 16 | if shooter.Id == 1 17 | x = x0 : max(stage.x) + stage.buildingWidth/2; 18 | else 19 | x = x0 : -1 : 0; 20 | end 21 | 22 | % Calculating the full trajectory y values without limiting it to the first 23 | % building being hit 24 | a = angle; 25 | u = velocity; 26 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 27 | 28 | % Limiting the trajectory to the first hit of the building, if any 29 | [hitIndex, x, y] = findHitBuildingId(stage, shooter, x, y); 30 | 31 | isWon = ~isempty(hitIndex) && ... 32 | hitIndex == target.buildingId && ... 33 | stage.x(hitIndex) - stage.buildingWidth/2 < x(end) && ... 34 | stage.x(hitIndex) + stage.buildingWidth/2 > x(end); 35 | 36 | figure(gcf) % bring the current figure to focus 37 | comet(x, y) 38 | 39 | end 40 | 41 | 42 | 43 | function [hitIndex, trajX, trajY] = findHitBuildingId(stage, player, x, y) 44 | 45 | hitIndex = []; 46 | 47 | if x(1) < x(end) 48 | % throwing towards the west direction 49 | i = player.buildingId; 50 | 51 | while i <= length(stage.x) && isempty(hitIndex) 52 | 53 | entranceWallFaceX = stage.x(i) - stage.buildingWidth/2; 54 | exitWallFaceX = stage.x(i) + stage.buildingWidth/2; 55 | 56 | mask = x >= entranceWallFaceX & ... 57 | x <= exitWallFaceX & ... 58 | y <= stage.y(i); 59 | 60 | mask = find(mask); 61 | 62 | if ~isempty(mask) 63 | hitIndex = i; 64 | trajX = x(1:mask(1)); 65 | trajY = y(1:mask(1)); 66 | end 67 | i = i + 1; 68 | end 69 | else 70 | % throwing towards the east direction 71 | i = player.buildingId; 72 | while i > 0 && isempty(hitIndex) 73 | 74 | entranceWallFaceX = stage.x(i) + stage.buildingWidth/2; 75 | exitWallFaceX = stage.x(i) - stage.buildingWidth/2; 76 | 77 | mask = x <= entranceWallFaceX & ... 78 | x >= exitWallFaceX & ... 79 | y <= stage.y(i); 80 | 81 | mask = find(mask); 82 | 83 | if ~isempty(mask) 84 | hitIndex = i; 85 | trajX = x(1:mask(1)); 86 | trajY = y(1:mask(1)); 87 | end 88 | i = i - 1; 89 | end 90 | end 91 | 92 | if isempty(hitIndex) 93 | trajX = x; 94 | trajY = y; 95 | end 96 | end -------------------------------------------------------------------------------- /Lec7/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %% Requirements 13 | % 14 | % 1. Use a bar chart with following specs to represents a 2D section of a 15 | % series of buildings. 16 | % 1.1 The first bar (building) must be centred at x = 25m 17 | % 1.2 There must be 15 buildings located 25m apart. 18 | % 1.3 Width of a building must be 20m (i.e. 80% of the gap between two 19 | % building centres) 20 | % 1.4 Buildings must have a random height between 100m to 200m, whole 21 | % numbers 22 | % 1.5 Both x and y axes limits must be 0 to 400m 23 | % 1.6 Set the x-axis label to be "Distance (m)", y-axis label to be 24 | % "Height (m), and the figure title to be "Gorillas in MATLAB" 25 | % 26 | % 2. Place the player 1 on top of a randomly selected building from 27 | % building #1 to #7. Denote the player by a pentagon of size 15 points. 28 | % 29 | % 3. Place the player 2 on top of a randomly selected building from 30 | % building #8 to #5. Denote the player by a pentagon of size 15 points. 31 | % 32 | % 4. Player 1 attacking player 2 with a banana! 33 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 34 | % 4.2 Prompt for and take the velocity (m/s) of the throw 35 | % 4.3 Calculate and plot the projectile from player 1's location towards 36 | % the player 2 as a line graph in red 37 | % 38 | % 5. Player 2 attacking player 1 with another banana 39 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 40 | % 4.2 Prompt for and take the velocity (m/s) of the throw 41 | % 4.3 Calculate and plot the projectile from player 2's location towards 42 | % the player 1 as a line graph in blue 43 | % 44 | % 6. When the program is replayed, the same figuer window should be used 45 | % after clearing all previous graphics 46 | 47 | 48 | %% Reset the envoronment 49 | 50 | % Setting up the parameters 51 | first = 25; 52 | step = 25; 53 | count = 15; 54 | buildingWidth = 20; 55 | minH = 100; 56 | maxH = 200; 57 | xmax = 400; 58 | ymax = 400; 59 | 60 | % Generating x and y vectors for the bar chart 61 | x = first : step : step * count; 62 | 63 | 64 | 65 | 66 | % Plotting the chart 67 | w = buildingWidth / step; 68 | 69 | 70 | 71 | 72 | %% Placing players (gorillas) 73 | 74 | % Placing player 1 75 | 76 | 77 | 78 | % Placing player 2 79 | 80 | 81 | 82 | 83 | %% Player 1 fires a banana 84 | 85 | % Taking inputs 86 | % disp('Gorilla (facing east):'); 87 | % a = round(input(' Angle (degrees)? ')); 88 | % u = round(input(' Velocity (m/s)? ')); 89 | 90 | % Computing the trajectory 91 | % x0 = 92 | % y0 = 93 | % x = 94 | % y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 95 | 96 | 97 | %% Player 2 fires a banana 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /Lec24/Lec24.m: -------------------------------------------------------------------------------- 1 | % Review 2 | % 3 | % Lec B3 4 | % April 02, 2020 5 | % 6 | 7 | %% Basic data types (classes) 8 | doubleScalar = 10.5; 9 | characterScalar = 'H'; 10 | logicalScalar = true; 11 | 12 | % Converting from one type to another 13 | 14 | dVal = double('H') % returns the ascii value of the character 15 | cVal = char(71) % returns the character represented by the ascii value 71 16 | 17 | 18 | % Creating vectors 19 | v1 = 1:5 20 | v2 = 1:2:10 21 | v3 = linspace(1,10) 22 | v4 = logspace(1,3) 23 | 24 | 25 | %% Matrix functions 26 | m = [1 2 3 27 | 4 5 6 28 | 7 8 9 29 | 10 11 12] 30 | 31 | % rearanging m to new dimensions by taking values column-wise 32 | reshape(m, 6,2) 33 | 34 | % rotating counterclockwise 35 | rot90(m) 36 | 37 | % rotating clockwise 38 | rot90(m, -1) 39 | 40 | % flipping 41 | flipud(m) 42 | fliplr(m) 43 | 44 | % column-wise sum 45 | sum(m) 46 | 47 | 48 | %% Cell Arrays 49 | cellArray = {12, [1:4], 'Hello', rand(3)} 50 | vec = cellArray{2} 51 | cellArray{3} = "Hello World" 52 | 53 | % Stuctures 54 | person = struct('FirstName', 'Winston', ... 55 | 'LastName', 'Churchill', ... 56 | 'DOB', 'November 30, 1874', ... 57 | 'Nationality', 'British'); 58 | 59 | disp(person.FirstName) 60 | person.LastName = 'Spencer-Churchill' 61 | 62 | rmfield(person, 'DOB') 63 | disp(person) 64 | 65 | 66 | %% Selection: IF/ELSEIF/ELSE 67 | 68 | clc 69 | val = randi(100) 70 | 71 | if val < 25 72 | disp('small') 73 | elseif val < 75 74 | disp('medium') 75 | else 76 | disp('large') 77 | end 78 | 79 | %% Selection: switch/case/otherwise 80 | 81 | day = input('Enter the day number (Monday = 1, etc): '); 82 | if day < 1 || day > 7 83 | error('Invalid day number') 84 | end 85 | 86 | switch day 87 | case 1 88 | disp('It''s the first day of the week') 89 | case {6, 7} 90 | disp('It''s weekend') 91 | otherwise 92 | disp('Yet another week day') 93 | end 94 | 95 | %% Repetition: FOR 96 | 97 | for i = 1:5 98 | fprintf('%d: Hello\n', i) 99 | end 100 | 101 | %% Repetition: WHILE 102 | clear 103 | clc 104 | 105 | n = 0; 106 | while n ~= 3 107 | n = randi(5); 108 | fprintf('Current number = %d\n', n); 109 | end 110 | 111 | 112 | %% Functions 113 | rad = 4; 114 | [area, circ] = circleinfo(rad) 115 | greet('Shrek') 116 | 117 | %% Low-level File Inputs 118 | 119 | clear 120 | clc 121 | 122 | fileId = fopen('twisters.txt', 'r'); % 'r' represents the read mode 123 | if fileId == -1 124 | error('Failed to open the file for reading') 125 | end 126 | 127 | while ~feof(fileId) 128 | line = fgetl(fileId); 129 | disp(line) 130 | end 131 | 132 | if fclose(fileId) ~= 0 133 | error('Failed to close the file') 134 | end 135 | 136 | %% Low-level File Outputs 137 | 138 | names = {'John', 'Elizabeth', 'Kyle', 'Rose'}; 139 | ages = [18, 22, 17, 16]; 140 | 141 | fid = fopen('mydata.txt', 'w'); 142 | 143 | if fid == -1 144 | error('Failed to open the file for writing') 145 | end 146 | 147 | for i = 1 : length(names) 148 | fprintf(fid, '%s: %d\n', names{i}, ages(i)); 149 | end 150 | 151 | if fclose(fid) ~= 0 152 | error('Failed to close the file') 153 | end -------------------------------------------------------------------------------- /Lec5/lec_5_1_vectors.m: -------------------------------------------------------------------------------- 1 | % Lecture 5 Part 1, Vectors 2 | % Chapter 2.1 Attaway 3 | 4 | % Various ways to create vectors 5 | % ============================== 6 | 7 | % Initializing a row vector 8 | v1 = [1 2 3 4 5] % using white space to separate elements 9 | v2 = [1,2, 3,4,5] % using comma to separate elements 10 | 11 | 12 | 13 | % using the colon operator 14 | v3 = 0:10 % 0 to 10, increments of 1 15 | v4 = 0:2:10 % 0 to 10 in increments of 2 16 | v5 = 0:3:10 % 0 to 10 in increments of 3. 17 | % Note the last value is 9 18 | v6 = 10:-1:0 % 10 to 0, decremented by 1 19 | v7 = 10:-3:0 % 10 to 0, decremented by 3 20 | 21 | 22 | % creating linearly spaced vectors using the "linspace" function 23 | v8 = linspace(1,4) % default count of 100 points from 1 to 4, inclusive 24 | v9 = linspace(1,4,10) % 10 points from 1 to 4, inclusive 25 | 26 | 27 | % creating logarithmically spaced vectors using the "logspace" function 28 | v10 = logspace(1,4) % default count of 50 points from 10^1 to 10^4, inclusive 29 | v11 = logspace(1,4,4) % 4 points from 10^1 to 10^4, inclusive 30 | 31 | 32 | % creating a row vector of random numbers 33 | v12 = rand(1, 5) % 1 row and 5 columns, uniformly distributed between 0 to 1 34 | v13 = randn(1,5) % 1 row and 5 columns, normally distributed 35 | 36 | 37 | % concatenating row vectors 38 | % ========================= 39 | v1 = [1 2 3 4] 40 | v2 = [-1 -2 -3] 41 | newVec = [v1 v2] % row concatenation 42 | 43 | 44 | % Referring to and Modifying Elements 45 | % =================================== 46 | clear 47 | clc 48 | 49 | v1 = rand(1, 5) % creating a random 1x5 vector 50 | thirdElement = v1(3) % access 3rd element 51 | v1(3) = 10 % assign 10 to the 3rd element 52 | 53 | 54 | v2 = v1([2 4 5]) % Extracting 2nd, 4th and 5th values of v1. 55 | % Vector [2 4 5] here is called an 56 | % index vector 57 | 58 | % Using "end" to access the last element 59 | v1(end) % referring to the last element 60 | v1(end) = 100 % assign 100 to the last element 61 | 62 | 63 | 64 | % Referring to an element beyond the last element 65 | v1(8) % Note that V1 has only 5 elements 66 | 67 | % Setting a value to an element beyond the last element 68 | v1(8) = 55 % Note that V1 is now extended to an 8-element vector 69 | % Elements 6 and 7 are set to 0 70 | % This is BAD practice because resizing a 71 | % vector this way is a slow operation. 72 | 73 | 74 | 75 | % Column Vectors 76 | % ============== 77 | 78 | % define column vectors by using semicolon to 79 | % separate elements, instead of 80 | % white space or comma 81 | cv1 = [1;2;3;4;5] 82 | 83 | % Alternatively, create a row vector and then use 84 | % the "transpose" operator (single quote) to 85 | % transpose it into a column vector 86 | cv2 = [1:5]' 87 | 88 | % creating a random column vector 89 | cv3 = rand(5, 1) % 5x1, uniformly distributed 90 | cv4 = randn(5, 1) % 5x1, normally distributed 91 | 92 | 93 | % Empty vectors and their use 94 | % =========================== 95 | emptyVec = [] 96 | 97 | v1 = 1:10 98 | 99 | v1(2) = [] % eliminates the 2nd element 100 | 101 | v1(end-3:end-1) = [] % eliminates the -------------------------------------------------------------------------------- /Lec8/lec_8_logical_expressions_and_operators.m: -------------------------------------------------------------------------------- 1 | % Lecture 8 Relational expressions (a.k.a. logical or Boolean expressions). 2 | % Logical vectors 3 | % Chapter 1.6 and 2.4 Attaway 4 | 5 | 6 | % Relational Expressions 7 | % ====================== 8 | 5 > 3 9 | 5 >= 3 10 | 5 < 1 11 | 5 <= 1 12 | 5 == 1 13 | 5 ~= 1 14 | 5 == 5 15 | 16 | 17 | % logical variables 18 | % ================= 19 | var1 = true; 20 | var2 = false; 21 | 22 | 23 | inputVal = input('Enter a number: '); 24 | isZero = inputVal == 0; 25 | isPositive = inputVal > 0; 26 | isNegative = inputVal < 0; 27 | 28 | 29 | % logical operators 30 | % ================= 31 | 32 | % logical OR and AND 33 | 2 < 4 || 'a' == 'c' % the second operand is not even evaluated -- short circuit 34 | 5 < 4 || 'a' == 'c' % both operands are evaluated 35 | 36 | 2 < 4 && 'a' == 'c' % both operands are evaluated 37 | 5 < 4 && 'a' == 'c' % the second operand is not even evaluated -- short circuit 38 | 39 | % negation 40 | ~ (4 < 5) 41 | ~ 4 < 5 % Refer chapter 2, page 67, Table 2.1 for operator precedence 42 | 43 | % function forms of OR and AND operators 44 | or(2 < 4, 'a' == 'c') 45 | and(2 < 4, 'a' == 'c') 46 | 47 | 48 | % exclusive OR 49 | xor(2 < 4, 'a' == 'c') 50 | 51 | v1 = xor(false, false) 52 | v2 = xor(false, true) 53 | v3 = xor(true, false) 54 | v4 = xor(true, true) 55 | 56 | 57 | % logical vectors 58 | % =============== 59 | clear 60 | 61 | vec = randi([50, 100], 1, 10) % a random vector 62 | v2 = vec > 75 % generates a logical vector 63 | v3 = v2 + 5 % an arithmatic operation on a logical vector 64 | % results a double vector 65 | 66 | mat = rand(3) 67 | mat2 = mat >= 0.5 68 | 69 | whos 70 | 71 | mat1 = true(4) 72 | mat2 = false(3,2) 73 | 74 | % type casting (i.e. changing type) 75 | mat = randi([-2, 2], 4) 76 | mat2 = logical(mat) % Note that all none-zero elements in mat are convered 77 | % to logical 1s (true) irresepctive of whether they are 78 | % positive or negative. 79 | % All zeros in mat are converted to logical 0s (false) 80 | 81 | 82 | % built-in logical functions 83 | v1 = logical([0 0 0 0 0 0 0]) 84 | v2 = logical([1 1 0 1 0 1 0]) 85 | v3 = logical([1 1 1 1 1 1 1]) 86 | 87 | any_1 = any(v1) 88 | any_2 = any(v2) 89 | any_3 = any(v3) 90 | 91 | all_1 = all(v1) 92 | all_2 = all(v2) 93 | all_3 = all(v3) 94 | 95 | mat = logical([0 1 1 0 1; 0 0 1 0 1; 0 1 1 0 1]) 96 | any_mat = any(mat) 97 | all_mat = all(mat) 98 | 99 | % finding indicies of non-zero elements 100 | find(v1) 101 | find(v2) 102 | find(v3) 103 | 104 | find(mat) 105 | 106 | 107 | v1 = logical([0 1 0 0 0 0 0]) 108 | v2 = logical([1 1 0 1 0 1 0]) 109 | v3 = v2 110 | 111 | isequal(v1, v2) 112 | isequal(v2, v3) 113 | 114 | mat1 = rand(3) < 0.5 115 | mat2 = rand(3) < 0.5 116 | mat3 = mat2 117 | 118 | isequal(mat1, mat2) 119 | isequal(mat2, mat3) 120 | 121 | 122 | % element-wise or array operators 123 | v1 = logical([0 1 0 0 0 0 0]) 124 | v2 = logical([1 1 0 1 0 1 0]) 125 | v3 = logical([1 1 1 1 1 1 1]) 126 | 127 | v1 == v2 % element-wise comparison. 128 | mat1 == mat2 129 | 130 | v1 | v2 % element-wise OR 131 | mat1 | mat2 132 | 133 | v1 & v2 % element-wise AND 134 | mat1 & mat2 135 | 136 | % function forms 137 | or(v1, v2) 138 | and(v1, v1) 139 | xor(v1, v2) 140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /Lec11/lec_11_3_vectorization.m: -------------------------------------------------------------------------------- 1 | % Vectorization and Timing 2 | % Chapter 5.4 and 5.5 3 | 4 | %% Ex. 1: Accessing elements which meets a criteria 5 | 6 | % Setting all elements of a matrix whos values are 5 and 8 (inclusive) 7 | % to 100 8 | 9 | clear 10 | clc 11 | 12 | mat = randi(9, 5); 13 | matBackup = mat; % Create a copy of the matrix because we are demonstrating 14 | % several methods 15 | 16 | disp('Original matrix') 17 | disp(mat) 18 | 19 | % non-vectorized code 20 | disp('Non-vectorized method (using a loop)') 21 | [rows,cols] = size(mat); 22 | for i = 1:rows 23 | for j = 1:cols 24 | if mat(i,j) >= 5 && mat(i,j) <= 8 25 | mat(i,j) = 100; 26 | end 27 | end 28 | end 29 | disp(mat) 30 | 31 | % vectorized code (longer form) 32 | disp('Using non-compact vectorized method') 33 | mat = matBackup; % restore the original matrix 34 | 35 | mask1 = mat>=5; 36 | mask2 = mat<=8; 37 | mask = mask1 & mask2; % note the element-by-element AND operator "&" 38 | mat(mask) = 100; % use logical indexing to set the element values 39 | 40 | disp(mat) 41 | 42 | % vectorized code (compact form) 43 | disp('Using compact vectorized method') 44 | mat = matBackup; % restore the original matrix 45 | 46 | mat(mat>=5 & mat<=8) = 100; 47 | 48 | disp(mat) 49 | 50 | %% Ex. 2: Counting the number of positive elements 51 | clear 52 | clc 53 | 54 | mat = randn(3); 55 | disp(mat) 56 | 57 | % non-vectorized code 58 | disp('Non-vectorized method (using a loop)') 59 | [rows,cols] = size(mat); 60 | count = 0; 61 | tic % Initialize a timer to measure the execution time 62 | for i = 1:rows 63 | for j = 1:cols 64 | if mat(i,j) > 0 65 | count = count + 1; 66 | end 67 | end 68 | end 69 | toc % Reports elapsed time the last "tic" 70 | fprintf('Count: %d\n\n', count) 71 | 72 | % vectorized code method 1 73 | disp('Vectorized method 1') 74 | tic 75 | count = sum(sum(mat>0)); 76 | toc 77 | fprintf('Count: %d\n\n', count) 78 | 79 | % vectorized code method 2 80 | disp('Vectorized method 2') 81 | tic 82 | count = sum(mat(:)>0); 83 | toc 84 | fprintf('Count: %d\n\n', count) 85 | 86 | %% Ex. 3: Extracting a portion of a vector up to a given "marker" 87 | 88 | clear 89 | clc 90 | 91 | % Assume, we need to extract the first portion of the following data vector 92 | % upto (but excluding) the first occurrence of -99. 93 | data = [21 90 67 47 91 11 74 -99 73 56 19 30 14 22 -99 89 8 25 6 44 2 89]; 94 | 95 | % Non-vectorized form (i.e. using a loop) 96 | % ======================================= 97 | i = 1; 98 | result = zeros(numel(data)); % Allocate up to the full length of the data 99 | % vector because in practice we might not know 100 | % where the "marker" will locate 101 | 102 | tic 103 | while i <= numel(data) && data(i) ~= -99 104 | result(i) = data(i); % copy the i-th element to the result 105 | i = i + 1; % increment the index i by 1 106 | end 107 | toc 108 | 109 | % Let's now remove all elements on the result vector from i-th element to 110 | % the end because they are empty. 111 | result = result(1:i-1); 112 | 113 | disp('Non-vecotroized result:') 114 | disp(result); 115 | 116 | % Vectorized form (i.e. with no loop) 117 | % =================================== 118 | tic 119 | markerIndicies = find(data == -99); 120 | result = data(1 : markerIndicies(1)-1); 121 | toc 122 | disp('Vecotroized result:') 123 | disp(result); 124 | -------------------------------------------------------------------------------- /LEC12/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 2 14 | ========================== 15 | 16 | 1. The stage must be set and the 2 players must be placed similar to 17 | the version 1. 18 | 19 | 2. The player 1 must played by a human (you) and the player 2 must be 20 | played by the computer (Kong). 21 | 22 | 3. You and Kong must keep playing alternatively until one of the 23 | following conditions is met: 24 | (a) Banana hits the top of the oposit player's building. In this 25 | case, the player who threw the banana wins. 26 | (b) You enter a velocity of 0, indicating you want to quit from 27 | the battle. 28 | 29 | 4. The angle and velocity of your throw must be taken interactively. 30 | 31 | 5. The angle and velocity of Kong's throw must be randomly generated. 32 | 33 | 6. The angles must be integer values between 0 and 90 degrees and the 34 | velocities must be integer values between 1 and 100 m/s. 35 | 36 | 7. Trajectory of a throw must stop at the first building it hits. 37 | 38 | 8. If a player wins, a message should be printed identifying the 39 | winner. If the game ended because you quit, it should be printed 40 | using an appropriate message. 41 | %} 42 | 43 | %% Code from Version 1 44 | 45 | % Reset the envoronment 46 | % --------------------- 47 | 48 | clf % clear previously plotted figure 49 | clc 50 | clear 51 | 52 | % Setting up the parameters 53 | first = 25; 54 | step = 25; 55 | count = 15; 56 | buildingWidth = 20; 57 | minH = 100; 58 | maxH = 200; 59 | xmax = 400; 60 | ymax = 400; 61 | 62 | % Generating x and y vectors for the bar chart 63 | stageX = first : step : step * count; 64 | rng('shuffle') % initialize the random number generator with a clock-based seed 65 | stageY = randi([minH, maxH], 1, length(stageX)); 66 | 67 | % Plotting the chart 68 | w = buildingWidth / step 69 | bar(stageX, stageY, w) 70 | hold on 71 | axis([0, xmax, 0, ymax]) 72 | xlabel('Position (m)'); 73 | ylabel('Height (m)'); 74 | title('{\itGorillas} in MATLAB'); 75 | 76 | 77 | % Placing players (gorillas) 78 | 79 | % Placing player 1 80 | index1 = randi([1, 7]); 81 | p1x = stageX(index1); 82 | p1y = stageY(index1) + 10; 83 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 84 | 85 | % Placing player 2 86 | index2 = randi([8, length(stageX)]); 87 | p2x = stageX(index2); 88 | p2y = stageY(index2) + 10; 89 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 90 | 91 | figure(gcf) % bring the current figure to focus 92 | 93 | %% Updated Code for Version 2 94 | 95 | activePlayer = 1 % Start with player 1 (human user) 96 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 97 | quit = false; % Set this to true the user inputs o for velocity 98 | 99 | while isempty(winner) && ~quit 100 | if activePlayer == 1 101 | % You (Player 1) fire a banana 102 | 103 | 104 | 105 | activePlayer = 2; % turn the next iteration to player 2 106 | else 107 | % Knog (Player 2) fires a banana 108 | 109 | 110 | activePlayer = 1; % turn the next iteration to player 1 111 | end 112 | end 113 | 114 | if ~isempty(winner) 115 | fprintf('%s Won!\n', winner) 116 | else 117 | disp('You quit the game! Play again you later.') 118 | end 119 | -------------------------------------------------------------------------------- /Gorillas/v3/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 3 14 | ========================== 15 | 16 | 1. Version 3 must fulfil the functional requirements of version 2. 17 | 18 | 2. In addition, this version must refactor code and use functions and 19 | structures to organize the progam code such that the main 20 | gorillas.m file controls the overall functionality and the control 21 | for while code related to specific functional blocks must be 22 | implemented as seprate functions. 23 | 24 | Requirements of Version 2 25 | ========================= 26 | 27 | 1. The stage must be set and the 2 players must be placed similar to 28 | the version 1. 29 | 30 | 2. The player 1 must played by a human (you) and the player 2 must be 31 | played by the computer (Kong). 32 | 33 | 3. You and Kong must keep playing alternatively until one of the 34 | following conditions is met: 35 | (a) Banana hits the top of the oposit player's building. In this 36 | case, the player who threw the banana wins. 37 | (b) You enter a velocity of 0, indicating you want to quit from 38 | the battle. 39 | 40 | 4. The angle and velocity of your throw must be taken interactively. 41 | 42 | 5. The angle and velocity of Kong's throw must be randomly generated. 43 | 44 | 6. The angles must be integer values between 0 and 90 degrees and the 45 | velocities must be integer values between 1 and 100 m/s. 46 | 47 | 7. Trajectory of a throw must stop at the first building it hits. 48 | 49 | 8. If a player wins, a message should be printed identifying the 50 | winner. If the game ended because you quit, it should be printed 51 | using an appropriate message. 52 | %} 53 | 54 | %% Code from Version 1 55 | 56 | stage = setstage(15); 57 | 58 | % Reset the envoronment 59 | % --------------------- 60 | 61 | % Placing players 62 | 63 | % Placing players 64 | p1 = setplayer(stage, 1); 65 | p2 = setplayer(stage, 2); 66 | 67 | figure(gcf) % bring the current figure to focus 68 | 69 | %% Updated Code for Version 2 70 | 71 | activePlayerId = 1; % Start with player 1 (human user) 72 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 73 | quit = false; % Set this to true the user inputs o for velocity 74 | 75 | while isempty(winner) && ~quit 76 | if activePlayerId == 1 77 | 78 | % You (Player 1) shoot a banana 79 | 80 | [a, u] = getshootparams; 81 | 82 | if u == 0 83 | quit = true; 84 | else 85 | isWon = shoot(stage, p1, p2, a, u); 86 | 87 | if isWon 88 | winner = 'You'; 89 | end 90 | end 91 | 92 | activePlayerId = 2; % turn the next iteration to player 2 93 | else 94 | 95 | % Knog (Player 2) fires a banana' 96 | 97 | [a, u] = calcshootparams; 98 | 99 | isWon = shoot(stage, p2, p1, a, u); 100 | 101 | if isWon 102 | winner = 'Kong'; 103 | end 104 | 105 | activePlayerId = 1; % turn the next iteration to player 1 106 | end 107 | fprintf('\n') 108 | end 109 | 110 | if ~isempty(winner) 111 | fprintf('%s Won!\n', winner) 112 | else 113 | disp('Come again to play later.') 114 | end 115 | -------------------------------------------------------------------------------- /Lec17/gorillas-v3-in-class-updates/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 3 14 | ========================== 15 | 16 | 1. Version 3 must fulfil the functional requirements of version 2. 17 | 18 | 2. In addition, this version must refactor code and use functions and 19 | structures to organize the progam code such that the main 20 | gorillas.m file controls the overall functionality and the control 21 | for while code related to specific functional blocks must be 22 | implemented as seprate functions. 23 | 24 | Requirements of Version 2 25 | ========================= 26 | 27 | 1. The stage must be set and the 2 players must be placed similar to 28 | the version 1. 29 | 30 | 2. The player 1 must played by a human (you) and the player 2 must be 31 | played by the computer (Kong). 32 | 33 | 3. You and Kong must keep playing alternatively until one of the 34 | following conditions is met: 35 | (a) Banana hits the top of the oposit player's building. In this 36 | case, the player who threw the banana wins. 37 | (b) You enter a velocity of 0, indicating you want to quit from 38 | the battle. 39 | 40 | 4. The angle and velocity of your throw must be taken interactively. 41 | 42 | 5. The angle and velocity of Kong's throw must be randomly generated. 43 | 44 | 6. The angles must be integer values between 0 and 90 degrees and the 45 | velocities must be integer values between 1 and 100 m/s. 46 | 47 | 7. Trajectory of a throw must stop at the first building it hits. 48 | 49 | 8. If a player wins, a message should be printed identifying the 50 | winner. If the game ended because you quit, it should be printed 51 | using an appropriate message. 52 | %} 53 | 54 | %% Code from Version 1 55 | 56 | stage = setstage(15); 57 | 58 | % Reset the envoronment 59 | % --------------------- 60 | 61 | % Placing players 62 | 63 | % Placing players 64 | p1 = setplayer(stage, 1); 65 | p2 = setplayer(stage, 2); 66 | 67 | figure(gcf) % bring the current figure to focus 68 | 69 | %% Updated Code for Version 2 70 | 71 | activePlayerId = 1; % Start with player 1 (human user) 72 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 73 | quit = false; % Set this to true the user inputs o for velocity 74 | 75 | while isempty(winner) && ~quit 76 | if activePlayerId == 1 77 | 78 | % You (Player 1) shoot a banana 79 | 80 | [a, u] = getshootparams; 81 | 82 | if u == 0 83 | quit = true; 84 | else 85 | isWon = shoot(stage, p1, p2, a, u); 86 | 87 | if isWon 88 | winner = 'You'; 89 | end 90 | end 91 | 92 | activePlayerId = 2; % turn the next iteration to player 2 93 | else 94 | 95 | % Knog (Player 2) fires a banana' 96 | 97 | [a, u] = calcshootparams; 98 | 99 | isWon = shoot(stage, p2, p1, a, u); 100 | 101 | if isWon 102 | winner = 'Kong'; 103 | end 104 | 105 | activePlayerId = 1; % turn the next iteration to player 1 106 | end 107 | fprintf('\n') 108 | end 109 | 110 | if ~isempty(winner) 111 | fprintf('%s Won!\n', winner) 112 | else 113 | disp('Come again to play later.') 114 | end 115 | -------------------------------------------------------------------------------- /Gorillas/v1/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %% Requirements 13 | % 14 | % 1. Use a bar chart with following specs to represents a 2D section of a 15 | % series of buildings. 16 | % 1.1 The first bar (building) must be centred at x = 25m 17 | % 1.2 There must be 15 buildings located 25m apart. 18 | % 1.3 Width of a building must be 20m (i.e. 80% of the gap between two 19 | % building centres) 20 | % 1.4 Buildings must have a random height between 100m to 200m, whole 21 | % numbers 22 | % 1.5 Both x and y axes limits must be 0 to 400m 23 | % 1.6 Set the x-axis label to be "Distance (m)", y-axis label to be 24 | % "Height (m), and the figure title to be "Gorillas in MATLAB" 25 | % 26 | % 2. Place the player 1 on top of a randomly selected building from 27 | % building #1 to #7. Denote the player by a pentagon of size 20 points. 28 | % 29 | % 3. Place the player 2 on top of a randomly selected building from 30 | % building #8 to #5. Denote the player by a pentagon of size 20 points. 31 | % 32 | % 4. Player 1 attacking player 2 with a banana! 33 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 34 | % 4.2 Prompt for and take the velocity (m/s) of the throw 35 | % 4.3 Calculate and plot the projectile from player 1's location towards 36 | % the player 2 as a line graph in red 37 | % 38 | % 5. Player 2 attacking player 1 with another banana 39 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 40 | % 4.2 Prompt for and take the velocity (m/s) of the throw 41 | % 4.3 Calculate and plot the projectile from player 2's location towards 42 | % the player 1 as a line graph in blue 43 | % 44 | % 6. When the program is replayed, the same figuer window should be used 45 | % after clearing all previous graphics 46 | 47 | 48 | %% Reset the envoronment 49 | clf % clear previously plotted figure 50 | 51 | % Setting up the parameters 52 | first = 25; 53 | step = 25; 54 | count = 15; 55 | buildingWidth = 20; 56 | minH = 100; 57 | maxH = 200; 58 | xmax = 400; 59 | ymax = 400; 60 | 61 | % Generating x and y vectors for the bar chart 62 | x = first : step : step * count; 63 | rng('shuffle') % initialize the random number generator with a clock-based seed 64 | y = randi([minH, maxH], 1, length(x)); 65 | 66 | % Plotting the chart 67 | w = buildingWidth / step; 68 | bar(x, y, w) 69 | hold on 70 | axis([0, xmax, 0, ymax]) 71 | xlabel('Position (m)'); 72 | ylabel('Height (m)'); 73 | title('{\itGorillas} in MATLAB'); 74 | 75 | 76 | %% Placing players (gorillas) 77 | 78 | % Placing player 1 79 | index1 = randi([1, 7]); 80 | p1x = x(index1); 81 | p1y = y(index1) + 10; 82 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 83 | 84 | % Placing player 2 85 | index2 = randi([8, length(x)]); 86 | p2x = x(index2); 87 | p2y = y(index2) + 10; 88 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 89 | 90 | 91 | %% Player 1 fires a banana 92 | 93 | % Taking inputs 94 | disp('Gorilla (facing east):'); 95 | a = round(input(' Angle (degrees)? ')); 96 | u = round(input(' Velocity (m/s)? ')); 97 | 98 | % Computing the trajectory 99 | x0 = p1x; 100 | y0 = p1y; 101 | x = p1x : xmax; 102 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 103 | plot(x, y, 'r-') 104 | figure(gcf) % bring the current figure to focus 105 | 106 | %% Player 2 fires a banana 107 | disp('Gorilla (facing west):'); 108 | a = round(input(' Angle (degrees)? ')); 109 | a = 180 - a; 110 | u = round(input(' Velocity (m/s)? ')); 111 | 112 | % Computing the trajectory 113 | x0 = p2x; 114 | y0 = p2y; 115 | x = p2x : -1 : 0; 116 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 117 | plot(x, y, 'b-') 118 | figure(gcf) % bring the current figure to focus -------------------------------------------------------------------------------- /Lec7/gorillas_v1.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %% Requirements 13 | % 14 | % 1. Use a bar chart with following specs to represents a 2D section of a 15 | % series of buildings. 16 | % 1.1 The first bar (building) must be centred at x = 25m 17 | % 1.2 There must be 15 buildings located 25m apart. 18 | % 1.3 Width of a building must be 20m (i.e. 80% of the gap between two 19 | % building centres) 20 | % 1.4 Buildings must have a random height between 100m to 200m, whole 21 | % numbers 22 | % 1.5 Both x and y axes limits must be 0 to 400m 23 | % 1.6 Set the x-axis label to be "Distance (m)", y-axis label to be 24 | % "Height (m), and the figure title to be "Gorillas in MATLAB" 25 | % 26 | % 2. Place the player 1 on top of a randomly selected building from 27 | % building #1 to #7. Denote the player by a pentagon of size 20 points. 28 | % 29 | % 3. Place the player 2 on top of a randomly selected building from 30 | % building #8 to #5. Denote the player by a pentagon of size 20 points. 31 | % 32 | % 4. Player 1 attacking player 2 with a banana! 33 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 34 | % 4.2 Prompt for and take the velocity (m/s) of the throw 35 | % 4.3 Calculate and plot the projectile from player 1's location towards 36 | % the player 2 as a line graph in red 37 | % 38 | % 5. Player 2 attacking player 1 with another banana 39 | % 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 40 | % 4.2 Prompt for and take the velocity (m/s) of the throw 41 | % 4.3 Calculate and plot the projectile from player 2's location towards 42 | % the player 1 as a line graph in blue 43 | % 44 | % 6. When the program is replayed, the same figuer window should be used 45 | % after clearing all previous graphics 46 | 47 | 48 | %% Reset the envoronment 49 | clf % clear previously plotted figure 50 | 51 | % Setting up the parameters 52 | first = 25; 53 | step = 25; 54 | count = 15; 55 | buildingWidth = 20; 56 | minH = 100; 57 | maxH = 200; 58 | xmax = 400; 59 | ymax = 400; 60 | 61 | % Generating x and y vectors for the bar chart 62 | x = first : step : step * count; 63 | rng('shuffle') % initialize the random number generator with a clock-based seed 64 | y = randi([minH, maxH], 1, length(x)); 65 | 66 | % Plotting the chart 67 | w = buildingWidth / step; 68 | bar(x, y, w) 69 | hold on 70 | axis([0, xmax, 0, ymax]) 71 | xlabel('Position (m)'); 72 | ylabel('Height (m)'); 73 | title('{\itGorillas} in MATLAB'); 74 | 75 | 76 | %% Placing players (gorillas) 77 | 78 | % Placing player 1 79 | index1 = randi([1, 7]); 80 | p1x = x(index1); 81 | p1y = y(index1) + 10; 82 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 83 | 84 | % Placing player 2 85 | index2 = randi([8, length(x)]); 86 | p2x = x(index2); 87 | p2y = y(index2) + 10; 88 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 89 | 90 | 91 | %% Player 1 fires a banana 92 | 93 | % Taking inputs 94 | disp('Gorilla (facing east):'); 95 | a = round(input(' Angle (degrees)? ')); 96 | u = round(input(' Velocity (m/s)? ')); 97 | 98 | % Computing the trajectory 99 | x0 = p1x; 100 | y0 = p1y; 101 | x = p1x : xmax; 102 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 103 | plot(x, y, 'r-') 104 | figure(gcf) % bring the current figure to focus 105 | 106 | %% Player 2 fires a banana 107 | disp('Gorilla (facing west):'); 108 | a = round(input(' Angle (degrees)? ')); 109 | a = 180 - a; 110 | u = round(input(' Velocity (m/s)? ')); 111 | 112 | % Computing the trajectory 113 | x0 = p2x; 114 | y0 = p2y; 115 | x = p2x : -1 : 0; 116 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 117 | plot(x, y, 'b-') 118 | figure(gcf) % bring the current figure to focus -------------------------------------------------------------------------------- /LEC12/gorillas_v1.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements 14 | 15 | 1. Use a bar chart with following specs to represents a 2D section of a 16 | series of buildings. 17 | 1.1 The first bar (building) must be centred at x = 25m 18 | 1.2 There must be 15 buildings located 25m apart. 19 | 1.3 Width of a building must be 20m (i.e. 80% of the gap between two 20 | building centres) 21 | 1.4 Buildings must have a random height between 100m to 200m, whole 22 | numbers 23 | 1.5 Both x and y axes limits must be 0 to 400m 24 | 1.6 Set the x-axis label to be "Distance (m)", y-axis label to be 25 | "Height (m), and the figure title to be "Gorillas in MATLAB" 26 | 27 | 2. Place the player 1 on top of a randomly selected building from 28 | building #1 to #7. Denote the player by a pentagon of size 20 points. 29 | 30 | 3. Place the player 2 on top of a randomly selected building from 31 | building #8 to #5. Denote the player by a pentagon of size 20 points. 32 | 33 | 4. Player 1 attacking player 2 with a banana! 34 | 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 35 | 4.2 Prompt for and take the velocity (m/s) of the throw 36 | 4.3 Calculate and plot the projectile from player 1's location towards 37 | the player 2 as a line graph in red 38 | 39 | 5. Player 2 attacking player 1 with another banana 40 | 4.1 Prompt for and take the angle of the throw (0 - 90 degrees) 41 | 4.2 Prompt for and take the velocity (m/s) of the throw 42 | 4.3 Calculate and plot the projectile from player 2's location towards 43 | the player 1 as a line graph in blue 44 | 45 | 6. When the program is replayed, the same figuer window should be used 46 | after clearing all previous graphics 47 | %} 48 | 49 | % Reset the envoronment 50 | % --------------------- 51 | 52 | clf % clear previously plotted figure 53 | clc 54 | clear 55 | 56 | % Setting up the parameters 57 | first = 25; 58 | step = 25; 59 | count = 15; 60 | buildingWidth = 20; 61 | minH = 100; 62 | maxH = 200; 63 | xmax = 400; 64 | ymax = 400; 65 | 66 | % Generating x and y vectors for the bar chart 67 | stageX = first : step : step * count; 68 | rng('shuffle') % initialize the random number generator with a clock-based seed 69 | stageY = randi([minH, maxH], 1, length(stageX)); 70 | 71 | % Plotting the chart 72 | w = buildingWidth / step; 73 | bar(stageX, stageY, w) 74 | hold on 75 | axis([0, xmax, 0, ymax]) 76 | xlabel('Position (m)'); 77 | ylabel('Height (m)'); 78 | title('{\itGorillas} in MATLAB'); 79 | 80 | 81 | % Placing players (gorillas) 82 | 83 | % Placing player 1 84 | index1 = randi([1, 7]); 85 | p1x = stageX(index1); 86 | p1y = stageY(index1) + 10; 87 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 88 | 89 | % Placing player 2 90 | index2 = randi([8, length(stageX)]); 91 | p2x = stageX(index2); 92 | p2y = stageY(index2) + 10; 93 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 94 | 95 | figure(gcf) % bring the current figure to focus 96 | 97 | % Player 1 fires a banana 98 | 99 | % Taking inputs 100 | disp('Gorilla (facing east):'); 101 | a = round(input(' Angle (degrees)? ')); 102 | u = round(input(' Velocity (m/s)? ')); 103 | 104 | % Computing the trajectory 105 | x0 = p1x; 106 | y0 = p1y; 107 | x = p1x : xmax; 108 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 109 | plot(x, y, 'r-') 110 | figure(gcf) % bring the current figure to focus 111 | 112 | % Player 2 fires a banana 113 | disp('Gorilla (facing west):'); 114 | a = round(input(' Angle (degrees)? ')); 115 | a = 180 - a; 116 | u = round(input(' Velocity (m/s)? ')); 117 | 118 | % Computing the trajectory 119 | x0 = p2x; 120 | y0 = p2y; 121 | x = p2x : -1 : 0; 122 | y = y0 + tand(a) * (x - x0) - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 123 | plot(x, y, 'b-') 124 | figure(gcf) % bring the current figure to focus -------------------------------------------------------------------------------- /Lec18/strings_in_matlab.m: -------------------------------------------------------------------------------- 1 | % In this script, we will demonstrate two different types of string 2 | % representations in MATLAB along with relaed operations. The two 3 | % representations are character arrays and string scalars (or string 4 | % objects) 5 | % 6 | % References: Attaway, chapter 7.1 to 7.4, excuding 7.2.4. 7 | % Lec #18, March 12, 2020. 8 | 9 | 10 | clear 11 | 12 | % Single character 13 | c = 'H'; 14 | 15 | % Character array 16 | myCharArray = 'Hello'; 17 | 18 | % A string scalar or string object. Note the double quotes. 19 | myString = "Hello"; 20 | 21 | 22 | % Let's check what is in the environment 23 | whos 24 | 25 | %% String Operators 26 | 27 | % Empty string 28 | str1 = ""; 29 | 30 | % Concatenating strings with + operator 31 | str2 = "Hello"; 32 | str3 = "World"; 33 | result = str2 + str3 34 | result2 = str2 + " " + str3 35 | 36 | % Accessing the char array stored 37 | % inside a string object 38 | str = "Lazy rabbit" 39 | str{1} % note the single quotes of the result 40 | 41 | str{1} = 'speedy turtle' 42 | 43 | 44 | %% String Functions 45 | 46 | % STRING: converts a regular character array to a string object 47 | charArray = 'Hello there!'; 48 | string(charArray) 49 | 50 | 51 | % STRLENGTH: retrns the length of character array in a string object 52 | % Note: the regular LENGTH function will not work with stirng 53 | % objects. 54 | str = "Hello everybody"; 55 | strlength(str) 56 | 57 | 58 | % BLANKS: creates a blank vector of characters. 59 | blankVec = blanks(4) 60 | 61 | % DEBLANK: removes trailing white spaces 62 | % in strings and character arrays 63 | deblank('Hello ') 64 | deblank("Hello ") 65 | deblank(' Hello ') 66 | deblank(" Hello ") 67 | 68 | % SRTRIM: removes leading and trailing white spaces 69 | % in strings and character arrays 70 | strtrim(' Hello ') 71 | strtrim(" Hello ") 72 | strtrim(' Hello World! ') 73 | strtrim(" Hello World! ") 74 | 75 | % STRCAT: concatenates stings (similar to + operator) 76 | str1 = "Hello"; 77 | str2 = "There"; 78 | strcat(str1, str2) 79 | strcat(str1, " ", str2) 80 | 81 | % SPRINTF: very similar to fprintf but this one returns a string instead of 82 | % dosplaying the ooutput on the command line; 83 | str = sprintf('The value of pi is %.2f', pi); 84 | disp(str) 85 | 86 | % UPPER and LOWER: Chaging case pf characterarays and strings 87 | upper('Hello') 88 | upper("World!") 89 | 90 | lower('Hello') 91 | lower("World!") 92 | 93 | 94 | % STRCMP and STRCMPI: case-sensitive and case-insensitive 95 | % string comparisons 96 | str1 = "Hello"; 97 | str2 = "hello"; 98 | str3 = "World!"; 99 | 100 | strcmp(str1, str2) 101 | strcmpi(str1, str2) 102 | 103 | strcmp(str1, str3) 104 | strcmpi(str1, str3) 105 | 106 | % STRFIND: finds all occurrences of a string inside another string 107 | str = "You cannot end a sentence with because because because is a conjunction."; 108 | strfind(str, "because") 109 | 110 | 111 | % STRREP: replaces all occurrences of a string with another one 112 | str = "the quick brown fox jumps over the lazy dog"; 113 | strrep(str, "the", "a") 114 | 115 | 116 | % ISLETTER: returns a logical vector which identifies letter positions 117 | % by logical true 118 | str = "y = m*x + b"; 119 | isletter(str) 120 | 121 | % ISSPACE: returns a logical vector which identifies white-space positions 122 | % by logical true 123 | str = "y = m*x + b"; 124 | isspace(str) 125 | 126 | 127 | % ISCHAR: returns logical true if the input argument is a character or a 128 | % character vector. 129 | ischar('h') 130 | ischar('Hello') 131 | ischar("Hello") % returns false because input is a string object 132 | ischar(rand(5)) 133 | 134 | 135 | % ISSTRING: returns logical true if the input argument is a string object 136 | isstring('h') 137 | isstring('Hello') 138 | isstring("Hello") % returns true because input is a string object 139 | isstring(rand(5)) 140 | 141 | 142 | % NUM2STR and STR2NUM: conversion from number to string and string to 143 | % number 144 | num2str(25) 145 | 146 | str2num("54") 147 | str2num('54') 148 | 149 | % STRTOC: string tokanization 150 | str = "You cannot end a sentence with because because because is a conjunction."; 151 | [token, remainder] = strtok(str) 152 | 153 | del = " "; 154 | 155 | while str ~= "" 156 | [token, str] = strtok(str, del); 157 | disp(token) 158 | end 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /Lec17/gorillas-v3/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 3 14 | ========================== 15 | 16 | 1. Version 3 must fulfil the functional requirements of version 2. 17 | 18 | 2. In addition, this version must refactor code and use functions and 19 | structures to organized the progam code such that the main 20 | gorillas.m file controls the overall functionality and the control 21 | for while code related to specific functional blocks must be 22 | implemented as seprate functions. 23 | 24 | Requirements of Version 2 25 | ========================= 26 | 27 | 1. The stage must be set and the 2 players must be placed similar to 28 | the version 1. 29 | 30 | 2. The player 1 must played by a human (you) and the player 2 must be 31 | played by the computer (Kong). 32 | 33 | 3. You and Kong must keep playing alternatively until one of the 34 | following conditions is met: 35 | (a) Banana hits the top of the oposit player's building. In this 36 | case, the player who threw the banana wins. 37 | (b) You enter a velocity of 0, indicating you want to quit from 38 | the battle. 39 | 40 | 4. The angle and velocity of your throw must be taken interactively. 41 | 42 | 5. The angle and velocity of Kong's throw must be randomly generated. 43 | 44 | 6. The angles must be integer values between 0 and 90 degrees and the 45 | velocities must be integer values between 1 and 100 m/s. 46 | 47 | 7. Trajectory of a throw must stop at the first building it hits. 48 | 49 | 8. If a player wins, a message should be printed identifying the 50 | winner. If the game ended because you quit, it should be printed 51 | using an appropriate message. 52 | %} 53 | 54 | %% Code from Version 1 55 | 56 | % Reset the envoronment 57 | % --------------------- 58 | 59 | clf % clear previously plotted figure 60 | clc 61 | clear 62 | 63 | % Setting up the parameters 64 | first = 25; 65 | step = 25; 66 | count = 15; 67 | buildingWidth = 20; 68 | minH = 100; 69 | maxH = 200; 70 | xmax = 400; 71 | ymax = 400; 72 | 73 | % Generating x and y vectors for the bar chart 74 | stageX = first : step : step * count; 75 | rng('shuffle') % initialize the random number generator with a clock-based seed 76 | stageY = randi([minH, maxH], 1, length(stageX)); 77 | 78 | % Plotting the chart 79 | w = buildingWidth / step; 80 | bar(stageX, stageY, w) 81 | hold on 82 | axis([0, xmax, 0, ymax]) 83 | xlabel('Position (m)'); 84 | ylabel('Height (m)'); 85 | title('{\itGorillas} in MATLAB'); 86 | 87 | 88 | % Placing players (gorillas) 89 | 90 | % Placing player 1 91 | index1 = randi([1, 7]); 92 | p1x = stageX(index1); 93 | p1y = stageY(index1) + 10; 94 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 95 | 96 | % Placing player 2 97 | index2 = randi([8, length(stageX)]); 98 | p2x = stageX(index2); 99 | p2y = stageY(index2) + 10; 100 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 101 | 102 | figure(gcf) % bring the current figure to focus 103 | 104 | %% Updated Code for Version 2 105 | 106 | activePlayerId = 1; % Start with player 1 (human user) 107 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 108 | quit = false; % Set this to true the user inputs o for velocity 109 | 110 | stage = struct('x', stageX, ... 111 | 'y', stageY, ... 112 | 'Count', count, ... 113 | 'buildingWidth', buildingWidth, ... 114 | 'step', step ... 115 | ); 116 | p1 = struct('x', p1x, 'y', p1y, 'Id', 1, 'buildingId', index1); 117 | p2 = struct('x', p2x, 'y', p2y, 'Id', 2, 'buildingId', index2); 118 | 119 | while isempty(winner) && ~quit 120 | if activePlayerId == 1 121 | 122 | % You (Player 1) shoor a banana 123 | 124 | % Taking inputs 125 | disp('You (facing east):'); 126 | a = round(input(' Angle (degrees)? ')); 127 | u = round(input(' Velocity (m/s)? ')); 128 | 129 | if u == 0 130 | quit = true; 131 | else 132 | isWon = shoot(stage, p1, p2, a, u); 133 | 134 | if isWon 135 | winner = 'You'; 136 | end 137 | end 138 | 139 | activePlayerId = 2; % turn the next iteration to player 2 140 | else 141 | 142 | % Knog (Player 2) fires a banana 143 | disp('Kong (facing west):'); 144 | a = randi(90); 145 | fprintf(' Angle: %d\n', a) 146 | a = 180 - a; 147 | u = randi([1 100]); 148 | fprintf(' Velocity: %d\n', u) 149 | 150 | isWon = shoot(stage, p2, p1, a, u); 151 | 152 | if isWon 153 | winner = 'Kong'; 154 | end 155 | 156 | activePlayerId = 1; % turn the next iteration to player 1 157 | end 158 | fprintf('\n') 159 | end 160 | 161 | if ~isempty(winner) 162 | fprintf('%s Won!\n', winner) 163 | else 164 | disp('Come again to play later.') 165 | end 166 | -------------------------------------------------------------------------------- /Lec12/gorillas_v2.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 2 14 | ========================== 15 | 16 | 1. The stage must be set and the 2 players must be placed similar to 17 | the version 1. 18 | 19 | 2. The player 1 must played by a human (you) and the player 2 must be 20 | played by the computer (Kong). 21 | 22 | 3. You and Kong must keep playing alternatively until one of the 23 | following conditions is met: 24 | (a) Banana hits the top of the oposit player's building. In this 25 | case, the player who threw the banana wins. 26 | (b) You enter a velocity of 0, indicating you want to quit from 27 | the battle. 28 | 29 | 4. The angle and velocity of your throw must be taken interactively. 30 | 31 | 5. The angle and velocity of Kong's throw must be randomly generated. 32 | 33 | 6. The angles must be integer values between 0 and 90 degrees and the 34 | velocities must be integer values between 1 and 100 m/s. 35 | 36 | 7. Trajectory of a throw must stop at the first building it hits. 37 | 38 | 8. If a player wins, a message should be printed identifying the 39 | winner. If the game ended because you quit, it should be printed 40 | using an appropriate message. 41 | %} 42 | 43 | %% Code from Version 1 44 | 45 | % Reset the envoronment 46 | % --------------------- 47 | 48 | clf % clear previously plotted figure 49 | clc 50 | clear 51 | 52 | % Setting up the parameters 53 | first = 25; 54 | step = 25; 55 | count = 15; 56 | buildingWidth = 20; 57 | minH = 100; 58 | maxH = 200; 59 | xmax = 400; 60 | ymax = 400; 61 | 62 | % Generating x and y vectors for the bar chart 63 | stageX = first : step : step * count; 64 | rng('shuffle') % initialize the random number generator with a clock-based seed 65 | stageY = randi([minH, maxH], 1, length(stageX)); 66 | 67 | % Plotting the chart 68 | w = buildingWidth / step 69 | bar(stageX, stageY, w) 70 | hold on 71 | axis([0, xmax, 0, ymax]) 72 | xlabel('Position (m)'); 73 | ylabel('Height (m)'); 74 | title('{\itGorillas} in MATLAB'); 75 | 76 | 77 | % Placing players (gorillas) 78 | 79 | % Placing player 1 80 | index1 = randi([1, 7]); 81 | p1x = stageX(index1); 82 | p1y = stageY(index1) + 10; 83 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 84 | 85 | % Placing player 2 86 | index2 = randi([8, length(stageX)]); 87 | p2x = stageX(index2); 88 | p2y = stageY(index2) + 10; 89 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 90 | 91 | figure(gcf) % bring the current figure to focus 92 | 93 | %% Updated Code for Version 2 94 | 95 | activePlayer = 1 % Start with player 1 (human user) 96 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 97 | quit = false; % Set this to true the user inputs o for velocity 98 | 99 | while isempty(winner) && ~quit 100 | if activePlayer == 1 101 | 102 | % You (Player 1) fire a banana 103 | 104 | % Taking inputs 105 | disp('You (facing east):'); 106 | a = round(input(' Angle (degrees)? ')); 107 | u = round(input(' Velocity (m/s)? ')); 108 | 109 | if u == 0 110 | quit = true; 111 | else 112 | 113 | % Computing the trajectory 114 | x0 = p1x; 115 | y0 = p1y; 116 | x = p1x : xmax; 117 | y = y0 + tand(a) * (x - x0) ... 118 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 119 | 120 | i = index1; 121 | hit = false; 122 | while i <= length(stageX) && ~hit 123 | 124 | entranceWallFaceX = stageX(i) - buildingWidth/2; 125 | exitWallFaceX = stageX(i) + buildingWidth/2; 126 | mask = x >= entranceWallFaceX & ... 127 | x <= exitWallFaceX; 128 | mask = find(mask); 129 | if y(mask(1)) < stageY(i) 130 | % Hits on the entrance surface 131 | hit = true; 132 | x(mask(1) + 1 : end) = []; 133 | y(mask(1) + 1 : end) = []; 134 | elseif y(mask(end)) < stageY(i) 135 | % Hits on the top of the surface 136 | hit = true; 137 | x(mask(end) + 1 : end) = []; 138 | y(mask(end) + 1 : end) = []; 139 | 140 | if i == index2 141 | % Winning case 142 | winner = 'You'; 143 | end 144 | end 145 | i = i + 1; 146 | end 147 | comet(x, y) 148 | figure(gcf) % bring the current figure to focus 149 | end 150 | 151 | activePlayer = 2; % turn the next iteration to player 2 152 | else 153 | 154 | % Knog (Player 2) fires a banana 155 | disp('Kong (facing west):'); 156 | a = randi(90); 157 | fprintf(' Angle: %d\n', a) 158 | a = 180 - a; 159 | u = randi([1 100]); 160 | fprintf(' Velocity: %d\n', u) 161 | 162 | % Computing the trajectory 163 | x0 = p2x; 164 | y0 = p2y; 165 | x = p2x : -1 : 0; 166 | y = y0 + tand(a) * (x - x0) ... 167 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 168 | plot(x, y, 'b-') 169 | figure(gcf) % bring the current figure to focus 170 | 171 | activePlayer = 1; % turn the next iteration to player 1 172 | end 173 | fprintf('\n') 174 | end 175 | 176 | if ~isempty(winner) 177 | fprintf('%s Won!\n', winner) 178 | else 179 | disp('You quit the game! Play again you later.') 180 | end 181 | -------------------------------------------------------------------------------- /Gorillas/v2/gorillas.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 2 14 | ========================== 15 | 16 | 1. The stage must be set and the 2 players must be placed similar to 17 | the version 1. 18 | 19 | 2. The player 1 must played by a human (you) and the player 2 must be 20 | played by the computer (Kong). 21 | 22 | 3. You and Kong must keep playing alternatively until one of the 23 | following conditions is met: 24 | (a) Banana hits the top of the oposit player's building. In this 25 | case, the player who threw the banana wins. 26 | (b) You enter a velocity of 0, indicating you want to quit from 27 | the battle. 28 | 29 | 4. The angle and velocity of your throw must be taken interactively. 30 | 31 | 5. The angle and velocity of Kong's throw must be randomly generated. 32 | 33 | 6. The angles must be integer values between 0 and 90 degrees and the 34 | velocities must be integer values between 1 and 100 m/s. 35 | 36 | 7. Trajectory of a throw must stop at the first building it hits. 37 | 38 | 8. If a player wins, a message should be printed identifying the 39 | winner. If the game ended because you quit, it should be printed 40 | using an appropriate message. 41 | %} 42 | 43 | %% Code from Version 1 44 | 45 | % Reset the envoronment 46 | % --------------------- 47 | 48 | clf % clear previously plotted figure 49 | clc 50 | clear 51 | 52 | % Setting up the parameters 53 | first = 25; 54 | step = 25; 55 | count = 15; 56 | buildingWidth = 20; 57 | minH = 100; 58 | maxH = 200; 59 | xmax = 400; 60 | ymax = 400; 61 | 62 | % Generating x and y vectors for the bar chart 63 | stageX = first : step : step * count; 64 | rng('shuffle') % initialize the random number generator with a clock-based seed 65 | stageY = randi([minH, maxH], 1, length(stageX)); 66 | 67 | % Plotting the chart 68 | w = buildingWidth / step 69 | bar(stageX, stageY, w) 70 | hold on 71 | axis([0, xmax, 0, ymax]) 72 | xlabel('Position (m)'); 73 | ylabel('Height (m)'); 74 | title('{\itGorillas} in MATLAB'); 75 | 76 | 77 | % Placing players (gorillas) 78 | 79 | % Placing player 1 80 | index1 = randi([1, 7]); 81 | p1x = stageX(index1); 82 | p1y = stageY(index1) + 10; 83 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 84 | 85 | % Placing player 2 86 | index2 = randi([8, length(stageX)]); 87 | p2x = stageX(index2); 88 | p2y = stageY(index2) + 10; 89 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 90 | 91 | figure(gcf) % bring the current figure to focus 92 | 93 | %% Updated Code for Version 2 94 | 95 | activePlayer = 1 % Start with player 1 (human user) 96 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 97 | quit = false; % Set this to true the user inputs o for velocity 98 | 99 | while isempty(winner) && ~quit 100 | if activePlayer == 1 101 | 102 | % You (Player 1) fire a banana 103 | 104 | % Taking inputs 105 | disp('You (facing east):'); 106 | a = round(input(' Angle (degrees)? ')); 107 | u = round(input(' Velocity (m/s)? ')); 108 | 109 | if u == 0 110 | quit = true; 111 | else 112 | 113 | % Computing the trajectory 114 | x0 = p1x; 115 | y0 = p1y; 116 | x = p1x : xmax; 117 | y = y0 + tand(a) * (x - x0) ... 118 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 119 | 120 | i = index1; 121 | hit = false; 122 | while i <= length(stageX) && ~hit 123 | 124 | entranceWallFaceX = stageX(i) - buildingWidth/2; 125 | exitWallFaceX = stageX(i) + buildingWidth/2; 126 | mask = x >= entranceWallFaceX & ... 127 | x <= exitWallFaceX; 128 | mask = find(mask); 129 | if y(mask(1)) < stageY(i) 130 | % Hits on the entrance surface 131 | hit = true; 132 | x(mask(1) + 1 : end) = []; 133 | y(mask(1) + 1 : end) = []; 134 | elseif y(mask(end)) < stageY(i) 135 | % Hits on the top of the surface 136 | hit = true; 137 | x(mask(end) + 1 : end) = []; 138 | y(mask(end) + 1 : end) = []; 139 | 140 | if i == index2 141 | % Winning case 142 | winner = 'You'; 143 | end 144 | end 145 | i = i + 1; 146 | end 147 | comet(x, y) 148 | figure(gcf) % bring the current figure to focus 149 | end 150 | 151 | activePlayer = 2; % turn the next iteration to player 2 152 | else 153 | 154 | % Knog (Player 2) fires a banana 155 | disp('Kong (facing west):'); 156 | a = randi(90); 157 | fprintf(' Angle: %d\n', a) 158 | a = 180 - a; 159 | u = randi([1 100]); 160 | fprintf(' Velocity: %d\n', u) 161 | 162 | % Computing the trajectory 163 | x0 = p2x; 164 | y0 = p2y; 165 | x = p2x : -1 : 0; 166 | y = y0 + tand(a) * (x - x0) ... 167 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 168 | plot(x, y, 'b-') 169 | figure(gcf) % bring the current figure to focus 170 | 171 | activePlayer = 1; % turn the next iteration to player 1 172 | end 173 | fprintf('\n') 174 | end 175 | 176 | if ~isempty(winner) 177 | fprintf('%s Won!\n', winner) 178 | else 179 | disp('You quit the game! Play again you later.') 180 | end 181 | -------------------------------------------------------------------------------- /Lec17/gorillas_v2.m: -------------------------------------------------------------------------------- 1 | % GORILLAS:This is a MATLAB implementation of a simplified 2 | % version of the game Gorillas which was first introduced 3 | % with MS-DOS. 4 | % 5 | % This project was initially adapted to the ENCMP course by Dr. Dileepan 6 | % Joseph. 7 | % 8 | % This code is released under MIT License 9 | % 10 | % Jan - April, 2020 11 | 12 | %{ 13 | Requirements for Version 2 14 | ========================== 15 | 16 | 1. The stage must be set and the 2 players must be placed similar to 17 | the version 1. 18 | 19 | 2. The player 1 must played by a human (you) and the player 2 must be 20 | played by the computer (Kong). 21 | 22 | 3. You and Kong must keep playing alternatively until one of the 23 | following conditions is met: 24 | (a) Banana hits the top of the oposit player's building. In this 25 | case, the player who threw the banana wins. 26 | (b) You enter a velocity of 0, indicating you want to quit from 27 | the battle. 28 | 29 | 4. The angle and velocity of your throw must be taken interactively. 30 | 31 | 5. The angle and velocity of Kong's throw must be randomly generated. 32 | 33 | 6. The angles must be integer values between 0 and 90 degrees and the 34 | velocities must be integer values between 1 and 100 m/s. 35 | 36 | 7. Trajectory of a throw must stop at the first building it hits. 37 | 38 | 8. If a player wins, a message should be printed identifying the 39 | winner. If the game ended because you quit, it should be printed 40 | using an appropriate message. 41 | %} 42 | 43 | %% Code from Version 1 44 | 45 | % Reset the envoronment 46 | % --------------------- 47 | 48 | clf % clear previously plotted figure 49 | clc 50 | clear 51 | 52 | % Setting up the parameters 53 | first = 25; 54 | step = 25; 55 | count = 15; 56 | buildingWidth = 20; 57 | minH = 100; 58 | maxH = 200; 59 | xmax = 400; 60 | ymax = 400; 61 | 62 | % Generating x and y vectors for the bar chart 63 | stageX = first : step : step * count; 64 | rng('shuffle') % initialize the random number generator with a clock-based seed 65 | stageY = randi([minH, maxH], 1, length(stageX)); 66 | 67 | % Plotting the chart 68 | w = buildingWidth / step; 69 | bar(stageX, stageY, w) 70 | hold on 71 | axis([0, xmax, 0, ymax]) 72 | xlabel('Position (m)'); 73 | ylabel('Height (m)'); 74 | title('{\itGorillas} in MATLAB'); 75 | 76 | 77 | % Placing players (gorillas) 78 | 79 | % Placing player 1 80 | index1 = randi([1, 7]); 81 | p1x = stageX(index1); 82 | p1y = stageY(index1) + 10; 83 | plot(p1x, p1y, 'p', 'MarkerSize', 20) 84 | 85 | % Placing player 2 86 | index2 = randi([8, length(stageX)]); 87 | p2x = stageX(index2); 88 | p2y = stageY(index2) + 10; 89 | plot(p2x, p2y, 'p', 'MarkerSize', 20) 90 | 91 | figure(gcf) % bring the current figure to focus 92 | 93 | %% Updated Code for Version 2 94 | 95 | activePlayer = 1; % Start with player 1 (human user) 96 | winner = ''; % Set this to the winner ('You' or 'Kong; when one of you win 97 | quit = false; % Set this to true the user inputs o for velocity 98 | 99 | while isempty(winner) && ~quit 100 | if activePlayer == 1 101 | 102 | % You (Player 1) fire a banana 103 | 104 | % Taking inputs 105 | disp('You (facing east):'); 106 | a = round(input(' Angle (degrees)? ')); 107 | u = round(input(' Velocity (m/s)? ')); 108 | 109 | if u == 0 110 | quit = true; 111 | else 112 | 113 | % Computing the trajectory 114 | x0 = p1x; 115 | y0 = p1y; 116 | x = p1x : xmax; 117 | y = y0 + tand(a) * (x - x0) ... 118 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 119 | 120 | i = index1; 121 | hit = false; 122 | while i <= length(stageX) && ~hit 123 | 124 | entranceWallFaceX = stageX(i) - buildingWidth/2; 125 | exitWallFaceX = stageX(i) + buildingWidth/2; 126 | mask = x >= entranceWallFaceX & ... 127 | x <= exitWallFaceX; 128 | mask = find(mask); 129 | if y(mask(1)) < stageY(i) 130 | % Hits on the entrance surface 131 | hit = true; 132 | x(mask(1) + 1 : end) = []; 133 | y(mask(1) + 1 : end) = []; 134 | elseif y(mask(end)) < stageY(i) 135 | % Hits on the top of the surface 136 | hit = true; 137 | x(mask(end) + 1 : end) = []; 138 | y(mask(end) + 1 : end) = []; 139 | 140 | if i == index2 141 | % Winning case 142 | winner = 'You'; 143 | end 144 | end 145 | i = i + 1; 146 | end 147 | comet(x, y) 148 | figure(gcf) % bring the current figure to focus 149 | end 150 | 151 | activePlayer = 2; % turn the next iteration to player 2 152 | else 153 | 154 | % Knog (Player 2) fires a banana 155 | disp('Kong (facing west):'); 156 | a = randi(90); 157 | fprintf(' Angle: %d\n', a) 158 | a = 180 - a; 159 | u = randi([1 100]); 160 | fprintf(' Velocity: %d\n', u) 161 | 162 | % Computing the trajectory 163 | x0 = p2x; 164 | y0 = p2y; 165 | x = p2x : -1 : 0; 166 | y = y0 + tand(a) * (x - x0) ... 167 | - 9.81 * (x - x0).^2/(2 * u^2 * (cosd(a))^2); 168 | 169 | plot(x, y, 'b-') 170 | figure(gcf) % bring the current figure to focus 171 | 172 | activePlayer = 1; % turn the next iteration to player 1 173 | end 174 | fprintf('\n') 175 | end 176 | 177 | if ~isempty(winner) 178 | fprintf('%s Won!\n', winner) 179 | else 180 | disp('Come again to play later. See you!') 181 | end 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------