A blog to help electrical engineers and students to learn electrical engineering topics. Basic Electrical Engineering, Power Systems, Electrical Machines, tec.. Now special course on MATLAB for Beginners.

Class

Class

Wednesday, October 26, 2016

MATLAB Script - Loop Control Part 1




In this lecture we will discuss about another flow control method – Loop control. A loop control is used to execute a set of commands repeatedly The set of commands is called the body of the loop.

MATLAB has two loop control techniques 
  1. Counted loops - executes commands a specified number of times. 
  2. Conditional loops - executes commands as long as a specified expression is true.
The counted loops are called ‘for’ loop and the conditional loops are called ‘while’ loop. The keyword “end” is used to show the end of a Loop.


For loop is used when the numer of iteration is known. FOR Repeats for specified number of times ALWAYS executes computation loop at least once. For loop creates a vector of the variable defined in the command and execute the body of the loop for all the values of the vector. 

The while- loop used when the number of loop iterations is unknown. Number of iteration is controlled by a condition. The condition is tested in each iteration and stop looping when it is false. While loop will execute the body of loop ONLY if while condition is met. 

Both Scripts and functions also allow to loop using for and while loops. 

Conditional Control in MATLAB Scripts with Examples




In this lecture we discuss more about programming in MATLAB. One main section in programming is flow control. There are many flow control commands in MATLAB. In this lecture we discuss the conditional flow control commands.
Conditional statements are commands that allows MATLAB to decide whether or not to execute some code that follows the statement

Conditional statements use relational operators like ==,~=,>,< (Note that are all scalar tests).

The basic syntax is


žIf the conditional expression is true, MATLAB runs the lines of code that are between the line with if and the line with end.
If the conditional expression is false, MATLAB skips the code between if and the line with else and runs the code up to end.