clc clear all %% Chapter 22 - Exmaple 3: disp('ABSTRACT') disp(' Example of the for-end loop for a summation') % Purpose: add the values of a general set of data % INPUTS disp(' ') disp('INPUTS') data=[2 7 4.5 2.3 6 5]; disp(' The input data is:') disp(data') % CODE number =length(data); % number of elements in data vector data_sum=0; % starting point for summation for j=1:1:number data_sum=data_sum + data(j); end % OUTPUTS disp('OUTPUTS') fprintf(' The summation of the data is %g\n\n',data_sum) %% Extra Examples % using loops and limited in addition, find the value of any two numbers % mulitplied together disp('EXTRA EXAMPLES') disp('Find the product of any two numbers') disp(' ') disp('METHOD 1 (for-end loop)- INPUTS') % INPUTS disp(' INPUTS') a = input(' Enter the first number: '); b = input(' Enter the second number: '); % CODE/OUTPUTS % Using a for-loop to find the product, a*b. sumpf=0; % Starting place for the sum for i=1:1:a sumpf=sumpf+b; end fprintf(' OUTPUTS\n The product is %g\n\n',sumpf) disp('METHOD 2 (while-end loop)- INPUTS') disp(' INPUTS') disp(' Same as listed above') sumpw=0; % starting place for the sum i=1; % starting place for the loop counter while (i<=b) sumpw=sumpw+a; i=i+1; end fprintf(' OUTPUTS\n The product is %g\n\n',sumpw)