ECE 1304 Introduction to Electrical and Computer Engineering Section 1.10 Program Structures in MATLAB
What is a Computer Program? A series of commands that instruct the computer to take information and do something useful with it.
Simple Procedural Program Start Input Data Perform Calculations Output Data End
Program with a Branching Structure Start Input Data 1 Option 1 Calculations ? Option 0 Calculations Output Data End
Program with a Branching Structure 1 ? 1 ? ? 1
Program with a Branching Structure 1 ? 1 1 ? ?
Program with a Looping Structure Start Input Data Loop Calculations 1 ? Output Data End
A Menu Driven Structure Method Main Menu 1. Option 1 2. Option 2 End Input Choice? Start 1 1 ? Option 1 1 2 ? Option 2 1 End ? End
Programming Structures in MATLAB MATLAB provides for programming structures using Conditional Statements Loops
Conditional Statements The general form for conditional statements is if (conditional_expression) statements end The conditional expressions use one of the relational operators, ==, >, >=, etc.
Conditional Statements The general form for conditional statements is if (conditional_expression_1) statements_1 elseif (conditional_expression_2) statements_2 else statements_3 end The conditional expressions use one of the relational operators, ==, >, >=, etc.
Example Conditional Statements Assuming x has a scalar value if (x >= 0) y = sqrt(x) end else y = -sqrt(-x)
Example Conditional Statements Assuming x has a scalar value if (x >= 25) y = 50*sqrt(x) elseif (x >= 0) y = 10*x else y = 0 end
Loops MATLAB has two structures for loops: for (counter = start:increment:end) statements end while (conditional_expression)
Example Loops m = 0; x(1) = 10; for k = 2:3:11; m = m + 1; x(m+1) = x(m) + k^2; end
Example Loops x = 5; k = 0; while (x < 25); k = k + 1; y(k) = 3*x; x = 2*x-1; end
Switch – Case Structure switch switch_expression case case_expression statements ... otherwise end
Switch – Case Structure n = input('Enter a number: '); switch n case -1 disp('negative one') case 0 disp('zero') case 1 disp('positive one') otherwise disp('other value') end