EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials Matlab Tutorial Loops in Matlab
Secondary Sidebar
PowerShell Tutorial
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

Loops in Matlab

By Priya PedamkarPriya Pedamkar

Loops in Matlab

Introduction to Loops in Matlab

In this article, we will learn about Loops in Matlab. Originally developed focusing on mathematical simulations, MATLAB had been great for working with static numerical data in vectors and matrices. But it can now read data from flat files, databases, cloud storage, data acquisition hardware and even live financial data feeds. MATLAB is very capable in the field of data science and is currently being widely applied in many different industries.

In all computer programming languages, there exist some ‘loop’ statements which are used for repeatedly executing instructions. More specifically, LOOPS allows the coder(s) to write shorter codes bypassing certain sets of repeating codes into conditional loops. Essentially, a loop is a set of instructions that is executed repeatedly until a certain condition is reached or as long as a certain condition is met.

loops in matlab

Loops in MATLAB

MATLAB uses for loops and while loops. There are also nested loops, which allow using either for or while loops within a loop.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

FOR Loop

The FOR loop is used when the number of iterations that a set of instructions is to be executed is known. Hence, it is used to execute code repeatedly as long as a certain condition is met. This condition is defined at the beginning of the FOR loop, also called as initialization of the FOR loop. Syntax of a for loop in MATLAB is as follows:

Syntax:

for index = value
…
program statements
… ;
end

Values can be one of the following forms:

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)
1. initialvalue:endvalue

Increases the index variable from the initial value to end value by 1, and repeats the execution of program statements until the index is greater than the end value.

for a = 10:20
fprintf(‘value of a: %d\n’, a);
end

Output:

initialvalue:endvalue

2. Initialvalue:step:endvalue:

Increases index by the value step on each iteration, or decreases when the step is negative.

Code:

for a = 1.0: -0.1: 0.0
disp(a);
end

Output:

Initialvalue:step:endvalue

3. valArray

Generates a column vector index from successive columns of array valArray on each iteration. The loop executes for n times, and n is the number of columns of valArray, set by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a cell array, string, or struct.

Code:

for a = [12, 14, 52, 61, 72] disp(a);
end

Output:

valArray

WHILE Loop

The while loop will execute the statements repeatedly as long as the specified condition is true. The syntax for the while loop is as below.

Syntax:

while <condition>
…
program statement
… ;
end

A condition is true when the result is not null and contains all nonzero elements (either logical or real numeric). Otherwise, the condition is false. The comparative value for the condition is defined before beginning the while loop, and the comparison condition is set in the while loop initialization.

For example, let us take the same condition as the first for loop example. Notice how the structure changes using the while loop.

Code:

a = 10;
while ( a < 20 )
fprintf(‘value of a: %d\n’, a);
a = a+1;
end

Here the initial value of ‘a’ is set before starting the loop, and the condition set in the loop is that ‘a’ should be less than 20. ‘a’ is then incremented by 1, and the loop reiterates as long as a < 20. This is how the result is shown, different from the result of the for a loop.

Output:

Loops in Matlab - 5

Since at a = 20 the condition is False, the code inside the loop is not executed. Hence the output shows only values of a from 10 to 19.

NESTED Loops

This means using one loop inside another loop. It could be using one for loop inside another for loop or one while loop inside another while loop creating compound statements. The resulting loop has to satisfy two conditions. That is, the condition in the outer loop is checked first, and if True, the condition in the second nested loop is checked. This allows the programmer to accomplish more complex conditional programming than simple numeric or Boolean tests.

loops in matlab

For example, a program to show all prime numbers between 1 and 100 would be as follows.

Code:

for i = 2:100
for j = 2:100
if (~mod(i,j))
break;
end
end
if (j > (i/j))
fprintf(‘%d is prime\n’, i);
end
end

Output:

Loops in Matlab - 7

..and so on until the prime number 97.

Loop Control Statements in Matlab

A control statement is a combination of conditions that govern the body of the loop to execute until the specified condition becomes False. Control statements also direct the syntax of the loop. For example, in a while loop, the comparative value(s) are defined before the loop initializes, whereas in a for loop the value conditions are defined when initializing the loop, in the for the statement.

Most importantly, loop control statements are used to control the execution of the loop or to change execution from the normal sequence of commands. MATLAB supports two specific loop control statements, the ‘break’ statement and the ‘continue’ statement. These commands are similarly used in other programming languages too.

Break Statement

The break command terminates execution of the for or while loop. Statements in the loop that are written after the break statement are skipped / not executed. In the case of nested loops, break exits only from the loop in which it is encountered. The control then passes to the statement after the end of the loop.

Continue Statement

The continue command is used for giving control to the next iteration of the loop. The continue statement works comparable to the break statement. Instead of forcing termination, ‘continue’ skips any code in between and forces the next iteration of the loop to be executed.

Conclusion

MATLAB allows using various types of loops in the code to handle looping requirements including: for loops, while loops and nested loops. There are also specific loop control statements to control the execution of these loops. Creating loops for repetitive statements is a great way of shortening the final code.

Recommended Articles

This is a guide to Loops in Matlab. Here we discuss various types of loops including: for loops, while loops and nested loops with loop control statements. You can also go through our other related articles to learn more –

  1. Loops in PowerShell
  2. Pie Chart in MATLAB
  3. Top 3 Types of Loops in Shell Scripting
  4. Guide to Nested Loop in C++
Popular Course in this category
MATLAB Training (3 Courses, 1 Project)
  3 Online Courses |  1 Hands-on Project |  8+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

R Programming Training (13 Courses, 20+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more