MATLAB is a matrix-based programming language used for numerical computations, data analysis, and visualization. It allows matrix manipulations, functions for computation and visualization, toolboxes for different applications, and integrated development environment for programming. MATLAB can be used for engineering and scientific calculations with graphical output. It has built-in functions, user-defined functions, 2D and 3D graphics capabilities, GUI tools, and interfaces with other languages like C and Fortran.
The name MATLAB stands for MATrix LABoratory.MATLAB is a high-performance language for technical computing.
It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports object-oriented programming.
These factor make MATLAB an excellent tool for teaching and research.
The frame work that I used for my Introduction to Matlab hour long course. Most of the instruction took place on a live Matlab screen, but this provided the framework
Matlab is basically a high level language which has many specialized toolboxes for making things easier for us.
Matlab stands for MATrix LABoratory.
The first version of MATLAB was produced in the mid 1970s as a teaching tool. MATLAB started as an interactive program for doing matrix calculations.
MATLAB has now grown to a high level mathematical language that can solve integrals and differential equations numerically and plot a wide variety of two and three Dimensional graphs.
The expanded MATLAB is now used for calculations and simulation in companies and government labs ranging from aerospace, car design, signal analysis through to instrument control and financial analysis.
In practice, it provides a very nice tool to implement numerical method.
- The desktop includes these panels:
Current Folder — Access your files.
Command Window — Enter commands at the command line, indicated by the prompt (>>).
Workspace — Explore data that you create or import from files.
- what we learn:
1- Introduction to Matlab.
2- MATLAB InstallationVersion 2018.
3- Assignment.
4- Operations in MATLAB.
5- Vectors and Matrices in MATLAB.
A basic overview, application and usage of MATLAB for engineers. It covered very basics essential that will help one to get started with MATLAB programming easily.
Provided by IDEAS2IGNITE
This is the slides of the UCLA School of Engineering Matlab workshop on Matlab graphics.
Learning Matlab graphics by examples:
- In 2 hours, you will be able to create publication-quality plots.
- Starts from the basic 2D line plots to more advanced 3D plots.
- You will also learn some advanced topics like fine-tuning the appearance of your figure and the concept of handles.
- You will be able to create amazing animations: we use 2D wave equation and Lorentz attractor as examples.
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
The name MATLAB stands for MATrix LABoratory.MATLAB is a high-performance language for technical computing.
It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports object-oriented programming.
These factor make MATLAB an excellent tool for teaching and research.
The frame work that I used for my Introduction to Matlab hour long course. Most of the instruction took place on a live Matlab screen, but this provided the framework
Matlab is basically a high level language which has many specialized toolboxes for making things easier for us.
Matlab stands for MATrix LABoratory.
The first version of MATLAB was produced in the mid 1970s as a teaching tool. MATLAB started as an interactive program for doing matrix calculations.
MATLAB has now grown to a high level mathematical language that can solve integrals and differential equations numerically and plot a wide variety of two and three Dimensional graphs.
The expanded MATLAB is now used for calculations and simulation in companies and government labs ranging from aerospace, car design, signal analysis through to instrument control and financial analysis.
In practice, it provides a very nice tool to implement numerical method.
- The desktop includes these panels:
Current Folder — Access your files.
Command Window — Enter commands at the command line, indicated by the prompt (>>).
Workspace — Explore data that you create or import from files.
- what we learn:
1- Introduction to Matlab.
2- MATLAB InstallationVersion 2018.
3- Assignment.
4- Operations in MATLAB.
5- Vectors and Matrices in MATLAB.
A basic overview, application and usage of MATLAB for engineers. It covered very basics essential that will help one to get started with MATLAB programming easily.
Provided by IDEAS2IGNITE
This is the slides of the UCLA School of Engineering Matlab workshop on Matlab graphics.
Learning Matlab graphics by examples:
- In 2 hours, you will be able to create publication-quality plots.
- Starts from the basic 2D line plots to more advanced 3D plots.
- You will also learn some advanced topics like fine-tuning the appearance of your figure and the concept of handles.
- You will be able to create amazing animations: we use 2D wave equation and Lorentz attractor as examples.
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
Simulink - Introduction with Practical ExampleKamran Gillani
Simulink® is a block diagram environment for multi-domain simulation and Model-Based Design. It supports simulation, automatic code generation, and continuous test and verification of embedded systems.
More instructions for the lab write-up1) You are not obli.docxgilpinleeanna
More instructions for the lab write-up:
1) You are not obligated to use the 'diary' function. It was presented only for you convenience. You
should be copying and pasting your code, plots, and results into some sort of "Word" type editor that
will allow you to import graphs and such. Make sure you always include the commands to generate
what is been asked and include the outputs (from command window and plots), unless the problem
says to suppress it.
2) Edit this document: there should be no code or MATLAB commands that do not pertain to the
exercises you are presenting in your final submission. For each exercise, only the relevant code that
performs the task should be included. Do not include error messages. So once you have determined
either the command line instructions or the appropriate script file that will perform the task you are
given for the exercise, you should only include that and the associated output. Copy/paste these into
your final submission document followed by the output (including plots) that these MATLAB
instructions generate.
3) All code, output and plots for an exercise are to be grouped together. Do not put them in appendix, at
the end of the writeup, etc. In particular, put any mfiles you write BEFORE you first call them.
Each exercise, as well as the part of the exercises, is to be clearly demarked. Do not blend them all
together into some sort of composition style paper, complimentary to this: do NOT double space.
You can have spacing that makes your lab report look nice, but do not double space sections of text
as you would in a literature paper.
4) You can suppress much of the MATLAB output. If you need to create a vector, "x = 0:0.1:10" for
example, for use, there is no need to include this as output in your writeup. Just make sure you
include whatever result you are asked to show. Plots also do not have to be a full, or even half page.
They just have to be large enough that the relevant structure can be seen.
5) Before you put down any code, plots, etc. answer whatever questions that the exercise asks first.
You will follow this with the results of your work that support your answer.
SAMPLE QUESTION:
Exercise 1: Consider the function
f (x,C)=
sin(C x)
Cx
(a) Create a vector x with 100 elements from -3*pi to 3*pi. Write f as an inline or anonymous function
and generate the vectors y1 = f(x,C1), y2 = f(x,C2) and y3 = f(x,C3), where C1 = 1, C2 = 2 and
C3 = 3. Make sure you suppress the output of x and y's vectors. Plot the function f (for the three
C's above), name the axis, give a title to the plot and include a legend to identify the plots. Add a
grid to the plot.
(b) Without using inline or anonymous functions write a function+function structure m-file that does
the same job as in part (a)
SAMPLE LAB WRITEUP:
MAT 275 MATLAB LAB 1 NAME: ...
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
2. INTRODUCTION
MATLAB (MATrix LABoratory)
Deals with matrix manipulations
Data defined : Array (in the form of row and column)
Special purpose computer programme
Perform engineering & scientific calculations with
graphical visualization
Provide Integrated Development Environment (IDE) for
programming
No. of predefined functions for computation and
visualization
3. Features and capabilities
MATLAB
(Programming Language)
Built-in Functions
User Defined Functions
Visualization
-2D Graphics
-3D Graphics
(With edit features)
GUI Tool
Toolboxes
(for dynamic simulations)
Simulink
SimpowerSystems
Fuzzy Logic
Neural Network
Communication
Control system
DSP
External Interface
(With C and FORTRAN)
4. Starting and Ending MATLAB
Starting:
Start / All Programs / MATLAB / R2010b / MATLAB
R2010b
Double clicking on MATLAB icon located on the
desktop
Ending:
Entering exit at MATLAB command prompt : >>exit
Entering quit at MATLAB command prompt: >>quit
Selecting Exit from file menu
Pressing Ctrl+Q at command prompt
5. Basic elements of Matlab’s desktop
Command Windows: Where all commands and programs
are run. Write the command or program name and hit
Enter.
Command History: Shows the last commands run on the
Command Windows. A command can be recovered clicking
twice
Current directory: Shows the directory where work will
be done.
Workspace: To see the variables in use and their
dimensions (if working with matrices)
Help (can also be called from within the command
windows)
Matlab Editor: All Matlab files must end with .m extension.
7. Basic elements of Matlab’s desktop
Some comments about the command window
Commands can be retrieved with arrow up /
arrow down keys ↓↑
Moving around the command line is possible
with left / right arrow keys . Go to the→ ←
beginning of the line with Inicio (Home) and to
the end with Fin (End). Esc deletes the whole
line.
A program can be stopped with Ctrl+c
8. Matlab editor
There can not be empty spaces in the name of
the Matlab files
Use “main_” for the name of the main programs, for
example: main_curvature
Write “;” at the end of a line If you don’t want that the
intermediate calculus is written in the window while the
program is running
Write “%” at the beginning of a line to write a comment
in the program
Write “…” at the end of a line if you are writing a very
long statement and you want to continue in the next line
9. MATLAB Editor Window
%Calculate volume of the cylinder
r=5; %Define radius of cylinder
h=10; %Define height of cylinder
volume=pi*r^2*h;
string=['The Volume of the cylinder
is',num2str(volume)];
disp(string);
10. Workspace
Temporary memory
All variables are cleared on ending/quit
MATALB
Save workspace : save <file name>
Particular value can be saved
Save <file name> <variable1 variable2 ….>
Load workspace: load <file name>
List of variables with details can generated
>>whos
>>who
11. Types of Files
.m files – Script files and function files (M-files)
.mat files – Binary data files (MAT-files)
.fig files – Figure windows
.mdl files – Model files (Simulink or
other toolboxes)
.mes files – MEX files
◦ Interface files write in C or FORTRAN
◦ Using mex function, mex compiles and link
source file into a shared library
12. Data input and output
Saving to files and recovering data:
Save <mat file_name> matrix1_name, matrix2_name
Load <mat file_name> matrix1_name, matrix2_name
save file_name matrix1_name –ascii (saves 8 figures after
the decimal point)
save file_name matrix1_name –ascii –double (saves 16
figures after the decimal point)
13. Getting help
help command ( >>help )
lookfor command ( >>lookfor)
LOOKFOR Search all M-files for keyword.
Help Browser ( >>doc )
helpwin command ( >>helpwin )
14. Important Commands
cd – Display/ Change current working directory
clc – Clear command window
clear – Clear content of workspace
clf – Clear content of current figure window
close – Close current figure window
^c – Abort / terminate the execution of current
program/command
date – Current date as date string
demo – Runs the demo programs
dir – List files/folders in present directory
exit – End (quit) a MATLAB session
help – Display help text in command window
15. Important Commands
load – Load saved workspace from working directory
lookfor – Search all M-files for a particular command or
keyword
path – Get/set MATLAB search path
pwd – Gives present working directory
quit – End a MATLAB session
save – Saves current workspace variables in working
directory
ver – Gives the MATLAB, SIMULINK and Toolboxes
version information
who – Generate the list of variables available in the
current workspace
whos – Generate the list of variables available in the
current workspace with their details (type, size, etc.)
16. Input/Output Commands
Input command
R=input(‘Enter the value of Resistance (in ohms): ’);
Output command
disp (variable name) or disp (‘Content of string’)
E.g.:- >>A=[1 2 3; 4 5 6];
>>disp(A);
>>disp(‘My Name is MATLAB’);
Display formatted string : fprintf (‘Text String’)
E.g.: fprintf(‘n Invalid data range.n Please enter new input.n’);
n : Newline; b: Backspace; t: Horizontal tab
f: Form feed; r: Carriage return; : Print backlash ()
’: Print apostrophe or single quote; %%: Print %
17. -- Continue…
Display a variable with text
fprintf (‘…Text…. Formatting elements ….Text….’, variable name);
Formatting elements : %-4.2d
% = Start of format element
- = Flags
4 = field width
2 = Precision
d = conversion character
E.g.: fprintf (‘The value of pi is %2.3f displayed up to three decimal digits’, pi);
Display more than one variable
fprintf (‘…Text…. %f…. %g… %c….’, variable1, variable 2, variable3 );
E.g.: >>x=2.34; y=3.15; z=2*pi;
>> fprintf (‘The value %f is less than %f is less than %g’, x, y, z);
18. -- Continue…
Field width and precision specifications
Field width – A string specifying minimum number of digits to
be printed (%6f)
Precision – A string including a period (.) specifying the number
of digits to be printed to the right of the decimal point (%6.2f)
Optional flags
‘-’ – Left justifies the number within the field (%-4.2d)
‘+’ – prints a sign character (+ or -) before the number (%+4.2d)
‘0’ – add zero before the number it is shorter than the defined
field (%04.2d)
Space character – Inserts a space before the value (% 4.2d)
19. -- Continue…
Conversion characters
%c – Single character
%d – Decimal notation (signed)
%e - Exponential notation (using lowercase e as 3.1415e+00)
%E - Exponential notation (using uppercase E as 3.1415E+00)
%f – Fixed point notation
%g – The shorter of %e or %f
%G – Same as %g, with uppercase E
%i – Decimal notation (signed)
%o – Octal notation (unsigned)
%s – String of characters
%u – Decimal notation (unsigned)
%x – Hexadecimal notation (using lowercase letters a-f)
%X - Hexadecimal notation (using uppercase letters A-F)
20. -- Continue…
>> x = [0 0.2 0.4 0.6 0.8 1.0]
Default format : >> x = 0:0.2:1;
Compact format: >> fprintf (‘%g ’, x);
Compact format with new line: >> fprintf (‘%gn ’, x);
Floating point format with width 4 and precision 2 in
newline: >> fprintf (‘%4.2fn ’, x);
Exponent format with new line: >> fprintf (‘%4.2en ’,
x);
21. Numbers and operations
Numerical Data:
Variables are defined with the assignment operator “=“. MATLAB is
dynamically typed, meaning that variables can be assigned without declaring their
type, and that their type can change. There is no need to define variables as integers,
reals, etc, as in other languages
◦ Integers: a=2
◦ Reals: x=-35.2
Maximum 19 significant figures
2.23e-3=2.23*10-3
Precision and formats: By defect, it uses a short format defect, but other formats
can be used:
>> format long (14 significant figures)
>> format short (5 significant figures)
>> format short e (exponential notation)
>> format long e (exponential notation)
>> format rat (rational approximation)
See in File menu: Preferences Command Windows→
23. Numbers and operations
Numerical data:
They’re case sensitive: x=5, X=7
Information about the variables used and their dimensions (if they’re
matrices): Workspace. Also typing
>> who
>> whos (gives more information)
To delete a variable (or several), run:
>> clear variable1 variable2
To delete all the variables, run: >> clear
Characteristic constants: pi=π, NaN (not a number, 0/0), Inf=∞.
Complex numbers:
i=sqrt(-1) (only i or j can be used), z=2+i*4, z=2+4i
◦ Careful not to use ‘i’ or “j” afterwards as a counter for a
loop when working with complex numbers.
24. Numbers and operations
Basic Arithmetic Operations:
Addition: +, Substraction -
Multiplication: *, Division: /
Power: ^
Priority Order: Power, division and multiplication,
and lastly addition and substraction. Use () to
change the priority.
26. Vectors and matrices
Defining vectors:
Row vectors; elements separated by spaces or comas
>> v =[2 3 4]
Column vectors: elements separated by semicolon (;)
>> w =[2;3;4;7;9;8]
Length of a vector w: length(w)
Generating row vectors:
◦ Specifying the increment h between the elements v=a:h:b
◦ Specifying the dimension n: linspace(a,b,n) (by default
n=100)
◦ Elements logarithmically spaced logspace(a,b,n) (n
points logarithmically spaced between 10a
y 10b.
By default
n=50)
27. Vectors and matrices
Defining matrices:
It’s not needed to define their size before hand (a size can be defined
and changed afterwards).
Matrices are defined by rows; the elements of one row are
separated by spaces or comas. Rows are separated by semicolon (;).
» M=[3 4 5; 6 7 8; 1 -1 0]
Empty matrix: M=[ ];
Information about an element: M(1,3), a row M(2,:), a column M(:,3).
Changing the value of an element: M(2,3)=1;
Deleting a column: M(:,1)=[ ], a row: M(2,:)=[ ];
28. Vectors and matrices
Defining matrices:
Generating the matrices:
◦ Generating a matrix full of zeros, zeros(n,m)
◦ Generating a matrix full of ones, ones(n,m)
◦ Initializing an identity matrix eye(n,m)
◦ Generating a matrix with random elements rand(n,m)
Adding matrices: [X Y] columns, [X; Y] rows
30. Operations with vectors and matrices
Operating vectors and matrices with scalars:
v: vector, k: scalar:
v+k addition
v-k sustraction
v*k product
v/k divides each element of v by k
k./v divides k by each element of v
v.^k powers each element of v to the k-power
k.^v powers k to each element of v
31. Operations with vectors and matrices
Operating vectors and matrices
+ addition
– subtraction
* matrix product
.* product element by element
^ power
.^ power element by element
left-division
/ right-division
./ or . right and left division element by element
Transposed matrix: B=A’ (in complex numbers, it returns the
conjugated transposed, to get only the trasposed: B=A.’)
32. Functions for vectors and matrices
sum(v) adds the elements of a vector
prod(v) product of the elements of a vector
dot(v,w) vectors dot product
cross(v,w) cross product
mean(v) (gives the average)
diff(v) (vector whose elements are the differenceof the elements of v)
[y,k]=max(v) or min(v)
maximum value or minimum valueof the elements of a vector (k gives the
position)
The maximum value of a matrix V is obtained with max(max(v)) and the
minimum with min(min(v))
Some of these operations applied to matrices, give the result by columns.
33. Functions for vectors and matrices
[n,m]=size(M) gives the number of rows and columns
Inverted matrix: B=inv(M), rank: rank(M)
diag(M): gives the diagonal of a matrix. sum(diag(M)) sums the
elements of the diagonal of M. diag(M,k) gives the k-th diagonal.
norm(M) norm of a matrix (maximum value of the absolute values
of the elements of M)
flipud(M) reorders the matrix, making it symmetrical over an
horizontal axis.
fliplr(M) ) reorders the matrix, making it symmetrical over a vertical
axis.
[V, landa]=eig(M) gives a diagonal matrix landa with the eigen
values, and another V whose columns are the eigenvectors of M
34. MATLAB Special Variables
ans Default variable name for results
pi Value of π
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number
35. Matrix Multiplication (Example)
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10
26 26 26
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10
26 26 26
[2x4]
[4x3]
[2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16
5 12 21 32
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16
5 12 21 32 c(2,4) =
a(2,4)*b(2,4)
Array Multiplication
36. - Continue …
>> a = [1 2 3 4;5 6 7 8]
a =
1 2 3 4
5 6 7 8
>> b = [1:4;1:4]
b =
1 2 3 4
1 2 3 4
>> a.*b
ans =
1 4 9 16
5 12 21 32
37. Sample Program
% Program to accept input for the matrix A
rows = input('Enter the number of rows: ');
cols = input('Enter the number of columns: ');
for a = 1:rows
for b =1:cols
A(a,b)=input('Enter number: ');
end;
end;
39. Sample Program
Enter the number of rows: 3
Enter the number of columns: 3
Enter number: 12
Enter number: 10
Enter number: 14
Enter number: 5
Enter number: 6
Enter number: 7
Enter number: 8
Enter number: 9
Enter number: 15
The given matrix is:
12 10 14
5 6 7
8 9 15
42. String Array Concatenation
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =
Hi there, Everyone!
» str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone!
Isn't MATLAB great?
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =
Hi there, Everyone!
» str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]
new_str2 =
Hi there, Everyone!
Isn't MATLAB great?
1x19 vector
1x9 vectorsUsing [ ] operator:
Each row must be
same length
Row separator:
semicolon (;)
Column separator:
space / comma (,)
For strings of different length:
• STRVCAT
• char
» new_str3 = strvcat(str, str2)
new_str3 =
Hi there,
Isn't MATLAB great?
» new_str3 = strvcat(str, str2)
new_str3 =
Hi there,
Isn't MATLAB great?
2x19 matrix
2x19 matrix
(zero padded)
1x19 vectors
43. Working with String Arrays
String Comparisons
strcmp: compare whole strings
strncmp: compare first ‘N’ characters
findstr: finds substring within a larger string
Converting between numeric & string arrays:
num2str: convert from numeric to string array
str2num: convert from string to numeric array
44. Sample Program
%Program for sring manipulations
str1 = input('Enter first string ','s');
str2 = input('Enter second string ','s');
str3 = input('Enter third string ','s');
catstr = strcat(strcat(str1,str2),str3);
disp('The concatenated string is')
disp(catstr)
if strcmp(str1,str2)
disp('The first two strings are same')
else
disp('The first two strings are not same')
end;
45. Logical Operations
» Mass = [-2 10 NaN 30 -11 Inf 31];
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
0
» all_pos = any(Mass>=0)
all_pos =
1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
» Mass = [-2 10 NaN 30 -11 Inf 31];
» each_pos = Mass>=0
each_pos =
0 1 0 1 0 1 1
» all_pos = all(Mass>=0)
all_pos =
0
» all_pos = any(Mass>=0)
all_pos =
1
» pos_fin = (Mass>=0)&(isfinite(Mass))
pos_fin =
0 1 0 1 0 0 1
= = equal to
> greater than
< less than
>= Greater or equal
<= less or equal
~ not
& and
| or
isfinite(), etc. . . .
all(), any()
find
Note:
• 1 = TRUE
• 0 = FALSE
48. Control Structures
if (Conditional statement)
Matlab Commands
end
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
if (Conditional statement)
Matlab Commands
else
Matlab Commands
end
If Statement Syntax
49. Sample Program – Selection (IF)
% Program to accept 3 numbers and display the largest no.
fn = input('Enter first number:');
sn = input('Enter Second number:');
tn = input('Enter third number:');
if ((fn > sn)& (fn > tn))
disp('The largest number is')
disp(fn)
elseif (sn > tn)
disp('The largest number is')
disp(sn)
else
disp('The largest number is')
disp(tn)
end;
50. Structures of control condicionated: switch
switch is similar to a sequence of if...elseif
switch_expresion=case_expr3
switch switch_expresion
case case_expr1,
actions1
case {case_expr2, case_expr3,case_expr4,...}
actions2
otherwise,
actions3
end
51. Sample Program – Selection (switch)
% Program to accept a choice from the user and perform
addition, subtraction, multiplication and division
testflag = 1;
disp('1.Add')
disp('2. Subtract')
disp('3. Multiply')
disp('4. Divide')
fn = input('Enter first number:');
sn = input('Enter second number:');
choice = input('Enter Choice');
switch choice
case 1
add = fn+sn;
disp('add =')
disp(add)
52. Sample Program – Selection (switch)
case 2
disp('sub =')
sub = fn - sn;
disp(sub)
case 3
disp('mul =')
mul = fn*sn;
disp(mul)
case 4
disp('div =')
div = fn/sn;
disp(div)
otherwise
disp('Invalid Choice')
testflag = 0;
end;
53. For loop syntax
for i=Index_Array
Matlab Commands
end
MATLAB Program
Write a program to find the sum of even numbers
between 0 and 21 using the for loop.
%Program to use for loop
%File name example2_for.m
Sum=0;
for j=0:2:21
Sum=Sum + j;
end
Sum
54. While Loop Syntax
while (condition)
Matlab Commands
end
MATLAB Program
Write a program to find the sum of even numbers between
0 and 21 using the fro loop.
%Program to use while loop
%File name example3_while.m
n=0;
Sum=0;
while n<21
Sum=Sum + n;
n=n+2;
end
Sum
55. Sample Program – Iteration (while)
% Program to accept a choice from the user and perform
addition, subtraction, multiplication and division
testflag = 1;
disp('1.Add')
disp('2. Subtract')
disp('3. Multiply')
disp('4. Divide')
fn = input('Enter first number:');
sn = input('Enter Second number:');
while (testflag == 1)
choice = input('Enter Choice');
switch choice
case 1
add = fn+sn;
disp('add =')
disp(add)
56. Sample Program – Iteration (while)
case 2
disp('sub =')
sub = fn - sn;
disp(sub)
case 3
disp('mul =')
mul = fn*sn;
disp(mul)
case 4
disp('div =')
div = fn/sn;
disp(div)
otherwise
disp('Invalid Choice')
testflag = 0;
end;
end;
59. Basic Task: Plot the function sin(x)
between 0≤x≤4π
Create an x-array of 100 samples between 0
and 4π.
Calculate sin(.) of the x-array
Plot the y-array
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
0 10 20 30 40 50 60 70 80 90 100
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
60. Plot the function e-x/3
sin(x) between
0≤x≤4π
Create an x-array of 100 samples between
0 and 4π.
Calculate sin(.) of the x-array
Calculate e-x/3
of the x-array
Multiply the arrays y and y1
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>y1=exp(-x/3);
>>y2=y*y1;
61. Plot the function e-x/3
sin(x) between
0≤x≤4π
Multiply the arrays y and y1 correctly
Plot the y2-array
>>y2=y.*y1;
>>plot(y2)
0 10 20 30 40 50 60 70 80 90 100
-0.3
-0.2
-0.1
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
63. - Continue
title(.)
xlabel(.)
ylabel(.)
>>title(‘This is the sinus function’)
>>xlabel(‘x (secs)’)
>>ylabel(‘sin(x)’)
0 10 20 30 40 50 60 70 80 90 100
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
This is the sinus function
x (secs)
sin(x)
>>grid;
64. Formatting a plot
>>Plot(x, y, ‘linespecifier’, ‘propertyname’, propertyvalue’)
Line specifier
Line style Marker style Colour
- Solid . Point y Yellow
: Dotted o Circle m Magenta
- Dash-dot x X-mark c Cyan
-- Dashed + Plus r Red
<none> No line * Star g Green
s Square b Blue
d Diamond w White
v Triangle(down) k Black
^ Triangle(up)
< Triangle(left)
> Triangle(right)
p Pentagram
h Hexagram
<none> No marker
65. - Continue
Property name and value
LineWidth
MarkerEdgeColor
MarkerFaceColor
Markersize
E.g.: f=50;
w=2*pi*f;
t=0:1e-3:0.04;
x=w*t;
y=sin(x);
plot(t, y, ‘- - rs’, ‘LineWidth’, 2.5, ‘MarkerEdgeColor’, ‘k’,
‘MarkerFaceColor’, ‘g’, ‘MarkerSize’, 8);
66. Multiple Plots
Using plot command
Plot the voltage (v=5sinwt) and current(i=2sin(wt-Φ))
flow through a circuit on the common axis.
%Multiple plot using plot command
%Filename Example1_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v=5*sin(w*t);
i= 2*sin((w*t)-phi);
plot(t,v,t,i)
title(“Multiple plot using plot command’);
xlabel(‘Time(sec)’);
ylabel(‘Voltage & Current’);
grid;
67. - Continue
Using hold command
%Multiple plot using hold command
%Filename Example2_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v1=sin(w*t);
plot(t,v1)
hold on; % Retain the current plot and certain axes properties
gtext(‘v1 = sin(wt)’);
v2=cos(w*t);
plot(t,v2)
hold off; % Reset axes properties to their defaults before drawing new plot
gtext(‘v2 = cos(wt)’);
title(‘Multiple plot using hold command’);
xlabel(‘Time(sec)’);
ylabel(‘V1 & V2’);
grid;
68. - Continue
Using line command
>>line (xdata, ydata, parameter_name, parameter_value)
%Multiple plot using line command
%Filename Example3_mp
t=0:1e-3:0.04; f=50; w=2*pi*f; phi=pi/3;
v1=sin(w*t);
v2=cos(w*t);
plot(t, v1, ‘- -’);
gtext(‘v1 = sin(wt)’);
line(t,v2);
gtext(‘v2=cos(wt)’);
title(‘Multiple plot using hold command’);
xlabel(‘Time(sec)’);
ylabel(‘V1 & V2’);
grid;
69. Adding legend to a plot
>> legend(‘string1’, ‘string2’,… pos)
Value Position Value Position
-1 Outside axis on the right
side
MC Middle and
centre
0 Auto placement with least
interferes with data
ML Middle and left
1 Upper right corner of the
plot (default)
MR Middle and right
2 Upper left corner of the
plot
BL Bottom left
3 Lower left corner of the
plot
BC Bottom centre
4 Lower right corner of the
plot
BR Bottom right
70. Formatting the text in Title, Labels and Legends
Modifier Effect Character
String
Greek Letter
bf Bold fonts alpha α
it Italic fonts beta β
rm Normal fonts gamma γ
fontname Type of font used theta θ
fontsize Size of font used phi Φ
- Subscript Delta Δ
^ Superscript delta δ
omega ω
Omega Ω
sigma σ
Sigma Σ
infty ∞
circ º
74. Plotting a complex data
Both real and imaginary can be plotted with
respect to time
>> plot(t, real(x));
>>plot(t, imag(x));
Real part can be plotted versus imaginary part
>>plot(x)
Complex function can be directly plotted as a
polar plot in terms of magnitude versus angle
>>polar(angle(x), abs(x))
75. - Continue…
E.g.: - x(t)=e-0.2t
(sint + jcost) for (0≤t ≤ 2π)
%Plot the complex function
%File name example_cf
% Real & Imaginary w.r.t time
t=0: pi/20 : 2*pi;
x=exp(-0.2*t) .* (sin(t) + i*cos(t));
figure(1);
plot(t, real(x), ‘-.’);
hold on;
plot(t, imag(x), ‘r’);
title(‘Plot of complex data versus time’);
xlabel(‘bfTime’);
ylabel(‘bfx(t)’);
legend(‘real’, ‘imaginary’);
grid;
76. - Continue…
% Real versus imaginary
figure(2);
plot(x);
title(‘Plot of complex data’);
xlabel(‘bfReal part’);
ylabel(‘bfImaginary part’);
grid;
% Polar plot
figure(3);
polar(angle(x), abs(x));
title(‘Plot of complex data as polar plot’);
grid;
77. Plotting a function
>> command(‘fun’, limits, linespecifiers)
◦ Command: ezplot or fplot
◦ fun: Function to be plotted
◦ limits: Limits of plot(optional)
◦ Linespecifiers: Type and colour of the line and marker (optional)
E.g: - Plot the function f(x) = 0.2x+(sin(2x)/x)
>>ezplot(‘(0.2*x)+(sin(2*x)/x)’);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi]);
>> fplot(‘(0.2*x)+(sin(2*x)/x)’, [-2*pi 2*pi –pi pi]);
81. MATLAB Function Programming
Functions and function files
>>function[output_argument]=function_name(input_argument);
>>function[output_argument1, output_argument2 …. ]
=function_name(input_argument1, input_argument2….);
E.g.: Write a program to solve the function
By writing a function file with ‘fun_1’, with the input to the function is
y and output f(y) for following values of x;
a) f(y) for y=4
b) f(y) for y=2, 4, 6, 8, 10
82. %Program to solve y(x) using function approach
Y=input(‘Enter the value of Y:’);
X=fun_1(Y);
disp(X);
%Function file fun_1
function X = fun_1(Y);
X=(Y.^3.*sqrt(2*Y+4))./(Y.^3+1).^2;
83. Differential equation solver
ODE - Ordinary Differential Equations
MATLAB ODE Solvers
Solver Problem type
/Accuracy
Description
ode23 Non-stiff /Medium One-step solver based on explicit Runge-Kutta (II
and III) method. In general faster but less accurate
than ode45
ode45 Non-stiff /Low One-step solver based on explicit Runge-Kutta (IV
and V) method. In general moderate accuracy
ode113 Non-stiff /Low to high Multi-step solver based on Adams method
ode15s Stiff /Moderate Multi-step solver of variable order (I to V)
ode23s Stiff /Low One-step low order solver based on a modified
Rosenbrock formula of order two
ode23t Moderately stiff /Low One-step solver based on trapezoidal rule
ode23tb Stiff /Low A low order solver, more efficient than ode15s
ode15i Solves fully implicit differential equations, variable
order method
84. ODE solver syntax
ODE = dy/dt = f(t, y)
>>[t, y] = solver_name(‘function’, tspan, y0);
E.g.:1) for 1≤ t ≤ 2 with initial condition y1=2.3 at t=0
for 1≤ t ≤ 2 with initial condition y2=1.2 at t=0
% create function file
function y1dot = ode_fun_1(t, y1) % Save file name ode_fun_1.m
y1dot = (t^2-2*y1)/t;
function y2dot = ode_fun_2(t, y2) % Save file name ode_fun_2.m
y2dot = (t^2-2*t)/t;
% Solve ODE
>>[t, y1] = ode45(‘ode_fun_1’, [1:0.2:2], 2.3);
>>[t, y2] = ode45(‘ode_fun_2’, [1:0.2:2], 1.2);
85. - Continue
E.g.:2) Write a program to find the step response of RL circuit for
the time range 0 to 1 sec with initial condition i=1 amps at t=0.
V = iR + L (di/dt); di/dt = (V-iR) / L
% Program to plot step response of series RL circuit
close all; clear; clc;
global R L V
R = 2; L=100e-3; V=10;
[t i] = ode45(‘RL_series’, [1:0.01:1], 1);
plot(t, i); grid; xlabel (‘Time(sec)’); ylabel (‘Current(amps)’);
%Function file RL_series
function idot = RL_series (t, i)
global R L V
idot = (1/L)*(V-i*R);
86. Calculus functions
Differentiation
>>diff(y) % dy/dx
>>diff(y,x) % dy/dx
>>diff(y,a) % dy/da
>>diff(y,t,2) % d2
y/dt2
Integration
>> int(y)
>> int(y,t)
>> int(y, a, b)
>> int (y, t, a, b)
87. Symbolic math functions
Sym x = sym(x)
>>a=5; b=sqrt (sym(a))
>>a=2/3; b=3/4; x = sym(a) + sym(b)
>>syms a b c; x = a^2 + 2*b + c
>>subs(x, a, 2)
>>subs(x, 2)
>>findsym(x)
>>findsym(x, 2)
88. ASSIGNMENT – MATLABASSIGNMENT – MATLAB
OVERVIEWOVERVIEW
Accept the roll number, name, 3 subject marks of a
student and print the details of the student with total
and average.
For problem (1), print the grade of the student as
pass(average>=50) or fail (average<50). Use If
statement
For problem (1), print the grade of the student as
Distinction (average>=90), First Class (average >=80
and <90), Second Class(average >=70 and <80), Third
Class (average>=60 and <70) otherwise Fail. Use
nested if statement
Accept a number and based on the choice of the user
display the square, cube, and quadruple of the number.
Use Switch case
Count the number of Vowels in a given string
Find the total number of characters in a given string
89. - Continue …
Check whether the original string and the reversed string are
same. If so, display palindrome string else not a palindrome
string.
Generate the Fibonacci Series 0 1 1 2 3 5 8 …N
Check whether the given number is perfect square (Number
divisible by 1 and itself)
List all Prime numbers between 1 and 100
Consider 3 subject marks for a student and use bar chart to
represent.
Consider a subject mark for 5 students and use bar chart to
represent
Perform Matrix Addition (Size mxn)
Find the roots and derivatives of the polynomial accepted from
the user.
Concatenate two vectors and sort.