代写 math matlab scala Programming MATLAB

Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2017

Outline
Conditional Statements

Program Flow Control

Recall Relational Expressions
􏰁 TherelationaloperatorsinMATLABare:
> greater than
< less than >= greater than or equals <= less than or equals == equality ~= inequality 􏰁 Theresultingtypeislogical1fortrueor0forfalse 􏰁 Thelogicaloperatorsare: || OR for scalars && AND for scalars | OR for matrices & AND for matrices ~ NOT xor logical XOR (true if only one of the arguments is true) all true if all elements are true any true if at least one element is true any, all: Examples Recall operator precedence 1. transpose (.’), power (.^), conjugate transpose (’), matrix power (^) 2. unary plus (+), unary minus (-), logical negation (~) 3. multiplication (.*), right division (./), left division (.\), matrix multi- plication (*), matrix right division (/), matrix left division (\) 4. addition (+), subtraction (-) 5. colon operator (:) 6. less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=)
7.
element-wise logical AND (&)
8.
element-wise logical OR (|)
9.
scalar logical AND (&&)
10.
scalar logical OR (||)

if Statement
􏰁 Theifstatementisusedtodeterminewhetherornotastatementor
group of statements is to be executed
􏰁 Generalform:
[statements before IF] if condition
[statements IF]
end
[statements after IF]
􏰁 Theconditionisanyrelationalexpression
􏰁 The[statementsIF](oraction)isanynumberofvalidstatements(including,
possibly, just one)
􏰁 Iftheconditionistrue,theexecutionflowis
􏰁 Iftheconditionisfalse,theexecutionflowis
[statements before IF]
[statements IF]
[statements after IF]
[statements before IF]
[statements after IF]

if-else Statement
􏰁 Theif-elsestatementchoosesbetweentwogroupofstatements
􏰁 Generalform:
[statements before IF-ELSE] if condition
[statements IF]
else
[statements ELSE]
end
[statements after IF-ELSE]
􏰁 Iftheconditionistrue,theexecutionflowis
􏰁 Iftheconditionisfalse,theexecutionflowis
[statements before IF-ELSE]
[statements IF]
[statements after IF-ELSE]
[statements before IF-ELSE]
[statements ELSE]
[statements after IF-ELSE]

Nested if-else Statements
􏰁 Tochoosefrommorethantwoactions,nestedif-elsestatements
can be used 􏰁 Generalform:
[statements before IF-ELSE] if condition_1
[action_1]
else
if condition_2
[action_2]
else
if [condition_3]
[action_3]
% etc: there can be many of these
else
[action] % the nth action end
end end
[statements after IF-ELSE]

elseif clause
􏰁 MATLABalsohasanelseifclausewhichshortensthecode(andcuts
down on the number of ends) 􏰁 Generalform:
[statements before IF-ELSE] if condition_1
[action_1]
elseif condition_2
[action_2]
elseif condition_3
[action_3]
% etc: there can be many of these
else
[action] % the nth action end
[statements after IF-ELSE]
􏰁 elseifdoesnotneedamatchingend

Example
script if_example.m
if isinf(x)
disp(’x is infinite’);
elseif isnan(x)
disp(’x is not-a-number’);
else
disp(’x is finite number’);
end
» x = 1;
» if_example
x is finite number
» x = 0/0;
» if_example
x is not-a-number
» x = 1/0;
» if_example
x is infinite

switch Statement
􏰁 Theswitchstatementcanfrequentlybeusedinplaceofa
if-elseif-else statement 􏰁 Generalform:
[statements before SWITCH] switch expression
case case_exp_1 [action_1]
case case_exp_2 [action_2]
case case_exp_3 [action_3]
% etc: there can be many of these
otherwise
[action_n]
end
[statements after SWITCH]
􏰁 expressionisevaluatedfirst,andifitsvaluematchesanyofthecases case_exp_1, case_exp_2, … then the corresponding action is executed
􏰁 Theotherwiseclausehandlesallotherpossiblevalues

Example
Several ways to define the norm of a vector X = [x1,x2,··· ,xn] n 􏰅􏰄n
􏰀 􏰄􏰀
􏰁 ∥X∥1 = |xi|, ∥X∥2 = 􏰃 |xi|2, ∥X∥∞ = max(|x1|,|x2|,··· ,|xn|)
i=1 i=1 script switch_norm.m
switch p case 1
N = sum(abs(x)); % equivalent with N = norm(x,1)
fprintf(’The norm_%d of the vector X is %6.3f\n’, p, N) case 2
N = sqrt(sum(abs(x).^2)); % equivalent with N = norm(x,2)
fprintf(’The norm_%d of the vector X is %6.3f\n’, p, N)
case inf N = max(abs(x)); % equivalent with N = norm(x,inf)
fprintf(’The norm_%d of the vector X is %6.3f\n’, p, N)
otherwise
N = sqrt(sum(abs(x).^2)); % equivalent with N = norm(x,2)
fprintf(’Wrong value of p! The norm_2 of the vector X is %6.3f\n’, N)
end
» x = [1, 4, -5, 3];
» p = Inf;
» switch_norm
The norm_Inf of the vector X is 5.000 » p = 1;
» switch_norm
The norm_1 of the vector X is 13.000
» p = 5;
» switch_norm
Wrong value of p! The norm_2 of the vector X is 7.141

Example
􏰁 Inascript,theuserissupposedtoentereithera’y’or’n’inresponseto a prompt. The user’s input is read into a character variable called letter. The script will print OK, continuing if the user enters either a ’y’ or ’Y’, or it will print OK, halting if the user enters a ’n’ or ’N’ or it will print Error if the user enters anything else.
letter = input(’Enter your answer: ’, ’s’);
switch letter
case {’y’, ’Y’}
disp(’OK, continuing’)
case {’n’, ’N’}
disp(’OK, halting’)
otherwise
disp(’Error’)
end

Example
􏰁 The function menu(HEADER, ITEM1, ITEM2, … ) displays a menu of push-buttons with labels ITEM1, ITEM2, .., and returns the result of the button push (1 for the first button, 2 for the second, etc. – or 0 if no button is pushed)
􏰁 Aswitchornestedifstatementisthenusedtoperform different actions based on the menu options
􏰁 Considerascriptthatpromptstheuserforavalueofavariable x, then uses the menu function to present choices between ’sin(x)’, ’cos(x)’, and ’tan(x)’. The script will print whichever function of x the user chooses.

Example
Using if-elseif-else approach
% Prints either sin, cos, or tan of x
% uses the menu function to choose
x = input(’Enter a value for x: ’);
choice = menu(’Choose a function’, ’sin’, …
’cos’, ’tan’);
if choice == 1
fprintf(’sin(%.1f) is %.1f\n’, x, sin(x))
elseif choice == 2
fprintf(’cos(%.1f) is %.1f\n’, x, cos(x))
elseif choice == 3
fprintf(’tan(%.1f) is %.1f\n’, x, tan(x))
else
disp(’Error!’)
end

Another example
Using switch approach
% Prints either sin, cos, or tan of x
% uses the menu function to choose
x = input(’Enter a value for x: ’);
choice = menu(’Choose a function’, ’sin’, …
’cos’, ’tan’);
switch choice
case 1
fprintf(’sin(%.1f) is %.1f\n’, x, sin(x))
case 2
fprintf(’cos(%.1f) is %.1f\n’, x, cos(x))
case 3
fprintf(’tan(%.1f) is %.1f\n’, x, tan(x))
otherwise
disp(’Error!’)
end

Example: one problem, three approaches
Consider the following piece-wise function:
 2x if 0 ≤ x < 0.5  1 if 0.5 ≤ x < 1.5 4−2x if1.5≤x<2  0 elsewhere f(x) = First approach 􏰁 "Translate"themathematicalexpressiontoaMATLAB expression function y = f(x) if (0 <= x) & (x < 0.5) y = 2*x; elseif (0.5 <= x) & (x < 1.5) y = 1; elseif (1.5 <= x) & (x < 2) y = 4 - 2*x; else y = 0; end end 􏰁 Theinputparameterxmustbeascalar.Whathappensifxisa vector ? Second approach 􏰁 Modifythecodebyconsideringxasavector function y = f(x) y = zeros(size(x)); idx_1 = find(0 <= x & x < 0.5); y(idx_1) = 2*x(idx_1); idx_2 = find(0.5 <= x & x < 1.5); y(idx_2) = 1; idx_3 = find(1.5 <= x & x < 2); y(idx_3) = 4 - 2*x(idx_3); end 􏰁 Ifxisascalar,theoutputofthefunctionisstillcorrect? Third approach - pure MATLAB 􏰁 InMATLAB,ifxisanumericalvalue,true*xgivesx,and false*x gives 0. function y = f(x) y = 2*x.*(0 <= x & x < 0.5) + ... end (0.5 <= x & x < 1.5) + ... (4-2*x).*(1.5 <= x & x < 2); 􏰁 Understandingtheexpression »x = [-0.2 -0.1 0.0 0.2 0.4 0.5 0.7 0.9 1.2 1.5 1.7 1.9 2]; » (0 <= x & x < 0.5) ans = 0 0 1 1 1 0 0 0 0 0 0 0 0 » (0.5 <= x & x < 1.5) ans = 0 0 0 0 0 1 1 1 1 0 0 0 0 » 2*x.*(0 <= x & x < 0.5) ans = 0.0 0.0 0.0 0.4 0.8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0