Practical 4: For- and While- Loops, If-statements
Command Sequence Controls
Debugging
Exercise: > Complete the exercises in the script M-file for this week. Run each cell separately and follow the instructions, making sure that you also add in the required code marked by starred lines. |
![]() |
> Fill in the correspondent commands doing what required within **....**. %% Practical 4 % Enter your name, student ID and the date here %--------------------------------------------------------- %% Exercise 1 % Use a for- loop to print out the square of integers from 1 up to %maxValue. maxValue = 10; > Use array operations from Practical 3 to solve the problem in Exercise 1. %% Exercise 2 % Use a while- loop to print out the square of integers from 1 up to % maxValue. maxValue = 10; %-------------------------------------------------------- %% Exercise 3 % Sam gets paid compound interest at a rate defined at 5% per annum. % Calculate his resulting investment each year and after 10 years. % Change the rate on the 8th year to 5.75%
rate = 0.05; %--------------------------------------------------------- %% Exercise 4 % create a graph that draws a straight line from the point (0,0) to % every other % point of the set (1,0), (1,1), (1,2), (1,3), (1,4). hold on %allows us to plot multiple lines on a graph hold off %--------------------------------------------------------- %% Exercise 5A % Use an if-else statement to check if an integer is either a prime % or a square number. % Make sure you change the value of the integer. % Check the help file to find a function that checks if a number is % prime. % note that this function works on both arrays and scalars. integer = 4; %-------------------------------------------------------------- %% Exercise 5B % Add some lines of code in the correct place above to check if the % number is divisible by 6 and assign it to variable FactorOf6. %% Exercise 5C % Modify the above code as follows: % Use a for-loop to check if each integer from 1 to 100 is a prime, % square or divisible by 6. % Collect the integers that meet the above conditions to the % correspondent arrays Prime, Square or FactorOf6. % Create count variables pCount, sCount and fCount which are updated % each time you find a new Prime, Square or FactorOf6 element and use % these counters to add new elements to your arrays. % Print Prime, Square & FactorOf6 after your for- loop is finished. |