MATLAB Control Statements
Objective: To study control structures (for, while, if, switch, break, continue, input/output functions, reading, and storing data).
If: If evaluates a logical expression and executes a group of statements based on the value of the expression.
Syntax of If Statement
if expression 1 statement1 elseif expression 2 statement 2 else statement 3 end
a is positive
Switch, case, and otherwise: Switch executes certain statements based on the value of a variable or expression. Its basic form is
switch switch expression case case expression statements case case expression statements . . . otherwise statements end
An evaluated switch expression is a scaler or string. An evaluated case expression a scaler, a string, or a cell array of scaler or strings. The switch block tests each case is until one of the cases is true.
Conditionally display different text depending on value entered at the command line.
result is 52
For: A for loop is a repetition control operation that allows us to accurately write a loop that wants to perform a particular number of times.
n = 1 a = 1 n = 2 a = 1 4 n = 3 a = 1 4 9 n = 4 a = 1 4 9 16 n = 5 a = 1 4 9 16 25 n = 6 a = 1 4 9 16 25 36 n = 7 a = 1 4 9 16 25 36 49 n = 8 a = 1 4 9 16 25 36 49 64 n = 9 a = 1 4 9 16 25 36 49 64 81 n = 10 a = 1 4 9 16 25 36 49 64 81 100
1 0.9000 0.8000 0.7000 0.6000 0.5000 0.4000 0.3000 0.2000 0.1000 0
1 5 8 17
while: The while loop repeatedly executes statements while a specified statement is true.
2 6 42
break: The break statement terminates execution of for or while loops. Statements in the loop that appear after the break statement are not executed.
continue: The continue statement is used for passing control to the next iteration of a for or while loop.
a = 1 a = 1 4 a = 1 4 9 a = 1 4 9 16 a = 1 4 9 16 25
pause: pause pauses the program for a set amount of time. If (…) is blank, then the program will pause until a key is pressed on the keyboard.
Load command: It loads data from a disk file into the current MATLAB workspace.
where filename is the name of the file to be load. If the file is a MAT-file, then all of the variables in the file will be restored with the name and types of the same as before.
E.g.: load -mat x.dat
Save: save command saves data from the current MATLAB workspace into a disk file.
save filename var1 var2 var3…
where filename is the name of the file where var1, var2, var3, etc. are saved. By default, the file name will be. mat. If no variable is specified, then the entire contents of the workspace will be saved.
If information must be exchanged between MATLAB and other programs, store the MATLAB data in ASCII format. If the data are used only in MATLAB, save the data in the mat file format.
X= [1.23 4.56 7.89 2.3] Save -ascii x.dat x;
Next TopicMATLAB 2-D Plots