%% INTRODUCTION TO MATLAB PART 4 %% Task D1a % Write a for loop to print out the answers for the three times table % from 1 to 12 x 3. clear all % clear the workspace for i=1:12 p = 3*i; disp(p) end %% Task D1b % Adapt the for loop so that answers for the three times table are stored % in a vector. clear all TimesTable = []; % create an empty vector to store results for i=1:12 p = 3*i; TimesTable = [TimesTable p]; end TimesTable %% Task D1b - alternative way of storing output in vector using counters clear all j = 1; for i=1:12 p = 3*i; TimesTable(j) = p; j = j+1; end TimesTable %% Task D1c % Repeat part D1(a) using a while loop. clear all i=1; while i =1 p = 3*i; disp(p) i = i - 1; end %% Task D1d (WHILE LOOP WITH FORMATTING) % Alter the code for (c) so the three times table is printed % backwards, i.e. from 12 x 3 down to 1 x 3. clear all i=12; while i>=1 p = 3*i; disp([num2str(i),' times 3 = ', num2str(p)]) i = i - 1; end %% Task D2a % Write a for loop to print out the elements of the sequence % $a_{n} = n^{2} + n + 1$ for $1 \leq n \leq 20$ . clear all for n=1:20 a = n.^2 + n + 1; disp([n,a]) end %% Task D2b % Adapt the loop to print out $S_{n}$ the sum of the first n terms of this % sequence. S = 0; for n=1:20 a = n.^2 + n + 1; S = S + a; disp([n,S]) end %% Task D2c % Adapt the code to store the values of $S_{n}$ in a vector and plot $S_{n}$ % as a function of n. clf clear all S = 0; for n=1:20 a = n.^2 + n + 1; S = S + a; p(n) = S; end plot(1:20,p,'o') xlabel('step number, n') ylabel('Sum of first n terms') %% Task D2d % Use a while loop to find the smallest value of n such that $S_{n}$ > 500. clear all S = 0; n = 0; while S