DEV Community

Cover image for MATLAB MONDAYS💥- Crash Course part-2
Aatmaj
Aatmaj

Posted on • Updated on <time datetime="2021-09-29T05:56:13Z" class="date-no-year">Sep 29</time>

MATLAB MONDAYS💥- Crash Course part-2

Welcome all! ❤️‍🔥 This Monday let us learn pre-baked MATLAB functions which we can just use off the shelf. After that we will learn the loop in MATLAB.🤟


In built Functions in MATLAB

MATLAB supports standard mathematical functions like sin, cos, log, exponentiation, square root, and many more.
However, unlike many languages, input for these functions can be an integer or even an matrix vectors.
Many MATLAB functions take in multiple inputs and return multiple outputs. eg. the min function can take in an array of numbers and output both, the smallest number and the position of the smallest number.
image

Similarly, the function plot takes in two matrices and plots their values. The plot connects all the points represented by the x,y pairs.
image

Another similer function is scatter() which generates the scatterplot of the functions.
image
MATLAB contains loads of other functions, whose documentation can be found out here

One more valuable function is rand(), which returns a random value.

>> x=rand()

x =

    0.8147
Enter fullscreen mode Exit fullscreen mode

Program control statements
MATLAB has the for loop syntax as follows

for i=a:b
 c=d
end
Enter fullscreen mode Exit fullscreen mode

Here the running variable i assumes values from 0,99
Python equivalent of this statement is

for i in range(a,b):
 #function
Enter fullscreen mode Exit fullscreen mode

Here is a sample program-

image

The if else statement has the following syntax

if a<b
 a=b
elseif a>b
 a=0
else
 b=0
end
Enter fullscreen mode Exit fullscreen mode

The Python equivalent is

if a<b:
 a=b
elif a>b:
 a=0
else:
 b=0
Enter fullscreen mode Exit fullscreen mode

Here is a sample

>> x=10;
>> if x<10
x=3
>> elseif x==10
>> x=pi
>> else
>> x=100
>> end
x =

    3.1416
Enter fullscreen mode Exit fullscreen mode

While loop
MATLAB also has the while loop with syntax as

while condition
statement
end
Enter fullscreen mode Exit fullscreen mode

For an infinite loop,

while true
 statement
end
Enter fullscreen mode Exit fullscreen mode

Here is an example which uses while loop- the Collatz conjuncture

>> for k=1:100
x=k;
while x>1
if mod(x,2)==0
x=x/2
else
x=3*x+1
end
end
end
Enter fullscreen mode Exit fullscreen mode

Note that % operator in python is replaced by the mod() function in MATLAB mod(a,b) is equivalent to a%b


That's all for this week. 🏆 Your comments really motivate me, so for any suggestions or doubts, please comment below 👇, and I will be happy to help 🙂 🎗️ Follow me for updates...
Also, you can gmail me for any suggestion or help 🙌
LinkedIn
Gmail

Bye for now 🖐
Meet you all soon👍

➕➖✖️➗

Discussion (0)