0% found this document useful (0 votes)
317 views

PRACTICAL FILE OF Matlab

Uploaded by

NARENDER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
317 views

PRACTICAL FILE OF Matlab

Uploaded by

NARENDER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

PRACTICAL FILE

MATLAB
INDEX
SR.NO PROGRAMS SIGNATURE
.
1. Introductionto MATLAB.
2. MATLAB Functions.
3. Writing your firstMATLAB program.
4. Write a program to perform simple calculation in
command window.
5. Write a program to check greater number in command
window.
6. Write a program to calculate simple interest in
command window.
7. Write a program to perform matrix addition in
command window.
8. Write a program to add two numbers in editor
window.
9. Write a program to find factorial of number in editor
window.
10. Write a program to display first 10 natural numbers in
editor window.
11. Write a program tofind addition of two numbers in
editor window.
12. Write a program to plot a line.
13. Write a program to create a multidimensional graph.
1. Introduction to MATLAB
MATLAB or Matrix Laboratory is a high-level programming language consisting of an

interactive environment mainly used for numeric computation, programming, and

visualization. It has been developed by MathWorks. The basic functions of MATLAB are

plotting of functions and data, the creation of user interfaces, matrix manipulations. It also

provides support for interfacing with other programming languages in C, C++, Fortran, and

Java. Besides, it is also used to analyse data, create models and applications, and also

develop algorithms. Along with all this, introduction to MATLAB also provides numerous

built-in functions for mathematical operations involving numerous calculations, performing

numerical methods, generating plots, and a lot of other functions. MATLAB also has a very

good scope in the automotive domain using Rapid control Prototyping or RCP used

extensively in medical, automotive, and aerospace domains.

Main components / highlights


In the above section, we studied the introduction to MATLAB, so now we’re going to learn

the components of MATLAB. MATLAB provides a lot of functionalities that can help in

computational mathematics. Below are the most common functions and mathematical

calculations used in MATLAB –

1. Dealing with Matrices and Arrays

2. 2-D and 3-D Plotting and graphics

3. Linear Algebra

4. Algebraic Equations

5. Non-linear Functions
6. Statistics

7. Data Analysis

8. Calculus and Differential Equations

9. Numerical Calculations

10. Integration

11. Transforms

12. Curve Fitting

13. Various other special functions

Characteristics
MATLAB is a versatile tool designed for computational mathematics and supports lots of

other operations. Below given are a few of the characteristics that make Matlab an

intelligent tool –

1. MATLAB contents are a huge library of built-in functions providing support for

various mathematical functions like filtering, optimization, Fourier analysis, linear

algebra, statistics, numerical integration, and solving differential equations.

2. MATLAB is a high-level language used for visualization, application development, and

numerical computation.

3. MATLAB provides support for creating custom plots and data visualization with its

built-in support for graphics.

4. MATLAB also supports an iterative environment helping to design and problem

solving along with iterative exploration.

5. MATLAB provides integration support with other languages like C, Java, Microsoft

Excel, and .NET for integrating MATLAB-based algorithms with external applications.
6. With its uniquely designed programming interface, MATLAB helps its users with

development tools for maximizing performance and improving code maintainability.

7. MATLAB also supports building applications with custom graphical interfaces.

Applications of MATLAB
As we discussed in the introduction to MATLAB, we will now learn about MATLAB’s

applications which are as follows: MATLAB is widely used in the industry as a tool for

mathematical computation and different streams of studies like physics chemistry,

engineering, mathematics, Etc. The various applications involving MATLAB are below –

1. Computational Finance

2. Control systems

3. Signal Processing and communication

4. Test and Measurement

5. Image and video processing

6. Computational biology

Advantages of MATLAB
Below are the advantages of MATLAB:

1. MATLAB is a compiler-independent tool and doesn’t require any compiler to execute

like as required in C, C ++. Codes are written in sentences and executed one by one.

2. Being compiler-independent makes MATLAB more efficient and productive.

3. MATLAB is a fourth-generation high-level language.

4. MATLAB coder is used to converting the code that is written in MATLAB to Java,

Python, C++, .NET, etc., making the MATLAB language more versatile.
5. Different languages can be used to implement scientific theories, and after building

the library files or .dll files, those can be directly implemented in MATLAB using other

languages.

6. The inbuilt rich library of MATLAB contains a library of the neural network, power

system, communication, fuzzy logic, hydraulics, Simulink, electromagnetics, electrics,

etc. Thus, using this reach library, it is always easy to develop and implement any

scientific simulation. These tools can be controlled by using built-in codes so that any

manual intervention of the control can be avoided in the model.

7. Complex mathematical operations like matrix multiplication and addition can be

easily accomplished in a single code by using MATLAB.

8. MATLAB also supports loops by using the length of code same or even shorter as

compared to C or C++ in a much convenient way.

9. MATLAB also supports the writing of user-defined functions, which are extremely

easy to implement and also can be stored in separate files for future use. This

potentially saves a lot of time writing the same code which is needed for different

operations and functions in regular use.

10. MATLAB allows the import and export of data to or from a text or excels file using a

single command which is very useful for analysis of previously recorded data.

MATLAB allows storage of data in excel files or .mat files.

11. Data can also be saved in variables with very simple commands, which are easy to

use by storing numbers in a vector or matrix where no use of loops is needed.

12. MATLAB also gives a feature to use GUI or graphical user interface using add and

drop boxes. On programming the proper functions of the code by using a graphical

user interface, the code is automatically generated by the program. The compilation
of the code is also very easy to implement, where the program is compiled in

MATLAB to a standalone application that can be opened on any system.

13. MATLAB offers a huge set of toolboxes and functions, allowing easy solving of CFD or

fluid flow and heat transfer problems very quickly.

14. MATLAB also provides REPL – read, evaluate, print, loop or interactive environment

to do mathematical computations and data visualization through graphs.

Disadvantages of MATLAB
Below are the disadvantages of MATLAB:

1. Cross-compiling of MATLAB code to other languages is very difficult and requires

deep MATLAB knowledge to deal with errors produced.

2. MATLAB is used mainly for scientific research and is not suitable for development

activities that are user-specific.

3. MATLAB is an interpreted language; thus, it can be very slow.

4. Poor programming practices can contribute to making MATLAB unacceptably slow.

5. MATLAB is more expensive. The license is very costly, and users need to buy each and

every module and need to pay for the same.

6. MATLAB is not known to create application deployment for installation like the task

done by others which includes the setting of files another executable that copies

during installation.
2. MATLAB Functions:
A function is a group of statements that together perform a task. In MATLAB, functions are
defined in separate files. The name of the file and of the function should be the same.
Functions operate on variables within their own workspace, which is also called the local
workspace, separate from the workspace you access at the MATLAB command prompt
which is called the base workspace.
Functions can accept more than one input arguments and may return more than one output
arguments.
Syntax of a function statement is −
function [out1,out2, ..., outN] = myfun(in1,in2,in3, ..., inN)

Example

The following function named mymax should be written in a file named mymax.m. It takes
five numbers as argument and returns the maximum of the numbers.
Create a function file, named mymax.m and type the following code in it −

function max =mymax(n1, n2, n3, n4, n5)

%Thisfunction calculates the maximum of the


% five numbers given as input
max = n1;
if(n2 > max)
max = n2;
end
if(n3 > max)
max = n3;
end
if(n4 > max)
max = n4;
end
if(n5 > max)
max = n5;
end
The first line of a function starts with the keyword function. It gives the name of the function
and order of arguments. In our example, the mymax function has five input arguments and
one output argument.
The comment lines that come right after the function statement provide the help text. These
lines are printed when you type −
help mymax
MATLAB will execute the above statement and return the following result −
This function calculates the maximum of the
five numbers given as input
You can call the function as −
mymax(34, 78, 89, 23, 11)
MATLAB will execute the above statement and return the following result −
ans = 89

Anonymous Functions:

An anonymous function is like an inline function in traditional programming languages,


defined within a single MATLAB statement. It consists of a single MATLAB expression and
any number of input and output arguments.
You can define an anonymous function right at the MATLAB command line or within a
function or script.
This way you can create simple functions without having to create a file for them.
The syntax for creating an anonymous function from an expression is
f = @(arglist)expression
Example
In this example, we will write an anonymous function named power, which will take two
numbers as input and return first number raised to the power of the second number.
Create a script file and type the following code in it −

power =@(x, n)x.^n;


result1 =power(7,3)
result2 =power(49,0.5)
result3 =power(10,-10)
result4 = power (4.5,1.5)
When you run the file, it displays −
result1 = 343
result2 = 7
result3 = 1.0000e-10
result4 = 9.5459

Primary and Sub-Functions:

Matlab functions:
Any function other than an anonymous function must be defined within a file. Each function
file contains a required primary function that appears first and any number of optional sub-
functions that comes after the primary function and used by it.
Primary functions can be called from outside of the file that defines them, either from
command line or from other functions, but sub-functions cannot be called from command
line or other functions, outside the function file.
Sub-functions are visible only to the primary function and other sub-functions within the
function file that defines them.
Example
Let us write a function named quadratic that would calculate the roots of a quadratic
equation. The function would take three inputs, the quadratic co-efficient, the linear co-
efficient and the constant term. It would return the roots.
The function file quadratic.m will contain the primary function quadratic and the sub-
function disc, which calculates the discriminant.
Create a function file quadratic.m and type the following code in it −

function[x1,x2]= quadratic(a,b,c)

%thisfunction returns the roots of


%a quadratic equation.
%It takes 3 input arguments
% which are the co-efficientsof x2, x and the
%constant term
%It returns the roots
d = disc(a,b,c);
x1 =(-b + d)/(2*a);
x2 =(-b - d)/(2*a);
end%endof quadratic

function dis = disc(a,b,c)


%function calculates the discriminant
dis =sqrt(b^2-4*a*c);
end%endofsub-function
You can call the above function from command prompt as −

quadratic(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans = 0.7321

Nested Functions:

You can define functions within the body of another function. These are called nested
functions. A nested function contains any or all of the components of any other function.
Nested functions are defined within the scope of another function and they share access to
the containing function's workspace.
A nested function follows the following syntax −
function x = A(p1, p2)
...
B(p2)
function y = B(p3)
...
end
...
end
Example
Let us rewrite the function quadratic, from previous example, however, this time the disc
function will be a nested function.
Create a function file quadratic2.m and type the following code in it −

function[x1,x2]= quadratic2(a,b,c)
functiondisc % nested function
d =sqrt(b^2-4*a*c);
end%endoffunction disc

disc;
x1 =(-b + d)/(2*a);
x2 =(-b - d)/(2*a);
end%endoffunction quadratic2
You can call the above function from command prompt as −

quadratic2(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans= 0.73205

Private Functions:

A private function is a primary function that is visible only to a limited group of other
functions. If you do not want to expose the implementation of a function(s), you can create
them as private functions.
Private functions reside in subfolders with the special name private.
They are visible only to functions in the parent folder.
Example
Let us rewrite the quadratic function. This time, however, the disc function calculating the
discriminant, will be a private function.
Create a subfolder named private in working directory. Store the following function
file disc.m in it −

function dis = disc(a,b,c)


%function calculates the discriminant
dis =sqrt(b^2-4*a*c);
end%endofsub-function
Create a function quadratic3.m in your working directory and type the following code in it −

function[x1,x2]= quadratic3(a,b,c)

%thisfunction returns the roots of


%a quadratic equation.
%It takes 3 input arguments
% which are the co-efficient of x2, x and the
%constant term
%It returns the roots
d = disc(a,b,c);

x1 =(-b + d)/(2*a);
x2 =(-b - d)/(2*a);
end%endof quadratic3
You can call the above function from command prompt as −

quadratic3(2,4,-4)
MATLAB will execute the above statement and return the following result −
ans= 0.73205

Global Variables:
Global variables can be shared by more than one function. For this, you need to declare the
variable as global in all the functions.
If you want to access that variable from the base workspace, then declare the variable at the
command line.
The global declaration must occur before the variable is actually used in a function. It is a
good practice to use capital letters for the names of global variables to distinguish them
from other variables.
Example
Let us create a function file named average.m and type the following code in it −

functionavg= average(nums)
global TOTAL
avg= sum(nums)/TOTAL;
end
Create a script file and type the following code in it −

global TOTAL;
TOTAL =10;
n =[34,45,25,45,33,19,40,34,38,42];
av= average(n)
When you run the file, it will display the following result −
av = 35.500
3. Writing Your First Program.
In this section we will show you how to write a simple program in MATLAB. To speed up
understanding, we will write a program that replicates the plot generated in the “Visual
Display” section.
 If you didn’t complete the previous sections, you can download the data
series HERE. Once you have downloaded the MATLAB file, place it in your
active MATLAB “Current Folder”.
 Writing a program for everything you do in MATLAB is the most efficient way
of operating within MATLAB. A program allows you to replicate difficult
processes quickly, save your work when it is not complete, fix mistakes before
they become problems, help you remember how you solved a particular
problem and much more.
 Start writing a new program by clicking new script at the top left of the
MATLAB window

 It is always wise to place some notes at the top of your program describing
the program’s purpose. It is also a good idea to place comments around
confusing parts of your code. There are often times when you will be working
as a team and everyone writes code differently. Do yourself and your team
members a favour and explain what you are doing.
 As a house keeping practice, I always write three lines of code at the top of
my program to avoid loitering variables and figures:
 “Clear all” clears all variables from the Workspace
 “Close all” closes all open figures
 “clc” clears the history of commands entered in the Command
Window
 Another important habit is to place a semi-colon”;” at the end of every
command in your program. This will suppress printing of the command in the
Command Window. However, occasionally it will be useful to allow the
computer to print a particular command.
 Type the commands in the script editor in the order that you would like
MATLAB to execute them:
 It is important to notice that if your variables are not saved in a file like
“data.mat”, they will be cleared by the first line of code
 Once you have written your code you will need to save it. Click on “Save” near
the upper left of your MATLAB window. Let’s name the program “plotSP”
 Once the file is saved you are free to run the program by clicking “Run” or by
typing “plotSP” and enter in the command window

 You should get a figure that looks like:

 Suppose that after you look at the graph, you decide that the real interesting
part of the series is the middle 2 quarters of the year. You can easily change
your program to only print the middle two quarters of the year by changing
the observation range to 64-189 (252/4=63).
 To make this change in your program, change the range
of dateNums and price as shown below:

 You should get a figure that looks like:

 Suppose further that you now love the data selection on the graph, but you
don’t like the unused space. You can fix this by adding the command “axis
tight”. For more information, see: Axis Scaling and Appearance
Saving Output
 You now love your data selection and your graph so much that you want to
save it as a Portable Network Graphic file or”.png”
 First you need to save the figure as a variable. Place the command “fig1 =
figure” before any plotting occurs (you could alternatively write fig1 = plot (x,
y)). This action saves all the following figure commands to the variable fig1.
 To save the final figure, you will need to add the command “save
as(fig1,’plotSP.png’)” at the end of all the figure commands. This saves the
variable fig1 as a file named “plotSP” of type”.png”.
 Once you have done all this, run the program again. You can view the .png file
in your MATLAB folder, which is located in your “Documents” folder on
Windows 7.
 Don’t forget to update your description of the program as your program no
longer plots the entire year; only the middle two quarters.
 Your final program should look like this:

 Your final output should look like this:


4. Write a program to perform simple calculation in command
window.
5. Write a program to check greater number in command window.
6.Write a program to calculate simple interest in command
window.
7.Write a program to perform matrix addition in command
window.
8.Write a program to perform addition of two numbers in editor
window.
INPUT-

OUTPUT-
9.Write a program to find factorial of number using for loop in
editor window.
INPUT-

OUTPUT-
10.Write a program to display first 10 natural numbers in editor
window.
INPUT-

OUTPUT-
11.Write a program to find addition of two numbers in editor
window.
INPUT-

OUTPUT-
12.Write a program to plot a line.
INPUT-

OUTPUT-
13.Write a program to create a multidimensional graph.
INPUT-

OUTPUT-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy