Decision and Loop Structure
fac = 2; lower = -1.65; %Normal 5% lower limit upper = 1.65; %Normal 95% upper limitif (fac >= lower) & (fac <= upper) disp('Value within range') elseif (fac > upper) disp('Value exceeds upper limit') else disp('Value below lower limit') end
Value exceeds upper limit
grade = 'A'switch grade case 'A' disp('Excellent') case 'B' disp('Good') case 'C' disp('Okay') case 'D' disp('Not good') case 'F' disp('Fail') otherwise disp('??') end
grade = A Excellent
for i = 1:5 disp(i) end
1 2 3 4 5
sum = 0; % initialize a variable (sum) startN = 1; % starting number endN = 100; % end numberfor i = startN:1:endN % define the index range the loop runs over sum = sum + i; end%prints a string combination disp(['The sum from ', num2str(startN), ' to ', ... num2str(endN),' is ',num2str(sum)]);
The sum from 1 to 100 is 5050
n = 10; fac = 1; %initialize factorial with 1for i = 1:n fac = fac*i; %calculate n!end disp( [num2str(n) '! = ' num2str(fac)] )
10! = 3628800
n = 10; i = n; fac = n; while i>1 i = i-1; fac = fac*i; % n!end disp( [num2str(n) '! = ' num2str(fac)] )
10! = 3628800
Display all prime numbers from 1 to 20
for i = 2:20 for j = 2:20 if (~mod(i,j)) %mod(a,m) returns the remainder after division of a by m break; % if factor j found, break % check if j == i end end if (j == i) % i is prime if the only factor is itself fprintf('%d is prime \n', i); endend
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime
i = 0; for t = 0:.01:10 i = i + 1; y(i) = sin(t); end t = 0:.01:10; y = sin(t);
clear tic; % Start a stopwatch timer t = 0:0.001:5000; for i = 1:length(t) if t(i)<1 y(i)=t(i); else y(i)=1; endend toc % Read the stopwatch timer clear tic; % Start a stopwatch timer t = 0:0.001:5000; y = nan(size(t)); for i = 1:length(t) if t(i)<1 y(i)=t(i); else y(i)=1; endend toc % Read the stopwatch timer
Elapsed time is 0.428066 seconds. Elapsed time is 0.102654 seconds.
%% funcname.m% help comments
function outvars = funcname (arglist) statements outvars = values;
function_name = @(argument_list) math_expression
circle = @(x, y) x^2 + y^2 circle(2,4) f1 = @(z,mu,sigma) (1/(sqrt(2*pi)*sigma))*exp(-(z-mu)^2/(2*sigma^2)); f1 (1, 0, 1)
circle = @(x,y)x^2+y^2 ans = 20 ans = 0.2420
x0 = ones(100,1); x1 = (1:100)'; x2 = 2 + 2*randn(100,1); u = randn(100,1); y = 2*x0 + 3*x1 + 5*x2 + u; X = [x0, x1, x2]; [b, se_b, e] = OLS(y, X);
OLS results report ------------------------------------------------------------ R-squared = 0.9999 sigma^2 = 1.0222 S.E. of estimate = 1.0110 Nobs = 100 Nvars = 3 ------------------------------------------------------------ Variable Coef sd t-stat ------------------------------------------------------------ b1 1.750179 0.242488 7.217585 b2 3.001874 0.003558 843.581077 b3 5.036739 0.044407 113.422452