SlideShare a Scribd company logo
Basics of Matlab Programming
Opio Phillip
Mountains of the Moon University
popio@mmu.ac.ug
MATLAB:- MATrix LABoratory
▸ Developed by Mathworks, Inc. http://www.mathworks.com
▸ It is an interactive, integrated, environment
▸ for numerical/symbolic, scientific computations and other
Apps
▸ shorter program development and debugging time than
other languages such as FORTRAN and C
▸ slow compared to FORTRAN or C
▸ easy to use
▸ automatic memory management; no need to declare
arrays
▸ etc
Getting Started with MATLAB
▸ Windows
double click MATLAB icon
▸ Linux Cluster
cd to bin folder in the installation dir
then ./matlab
▸ Either case it opens a MATLAB window with >> prompt
▸ To stop, type quit or exit at the command prompt >>
Current Folder
Files in the
current folder
Work Space
a 4
b 6
c 10
Command Window
Input Commands at the command line
prompt ≫
eg.
≫ a= 4;
≫ b=6;
≫ c=a+b;
Variable and File Names
▸ case sensitive, e.g., fname and fName are different names
▸ can be a mix of letters, digits, and underscores (e.g.,
vector A)
▸ variable namws always start with a letter e.g., xy or x2y
▸ maximum of 63 characters
▸ reserved characters: % = + - ; : ’ [ ] ( ) , # $ &
ˆ ! ∼ can NOT be used
▸ No space in the names e.g class marks not allowed
Uses of the characters % = ; ,
▸ % for adding comments, %% creates a shell in mfile
▸ = to asign a value to a variable e.g c=10
▸ ;
(i) suppresses output in the command window
(ii) delimits commands in the same line e.g clear;close all;
a=4;b=5;
(iii) seperate rows e.g. d=[2;3;4];
▸ ,
(i) seperate columns e = [4,2,3,1];
(ii) delimits commands in the same line e.g k = 4,m=12
Uses of the characters [] () :
▸ []
(i) for arrays e.g p =[12,3]
(ii) delete contents of arrays e.g x = [] deletes contents of x
▸ ()
(i) matrix indexing e.g t =[2,3,4], s=t(1,2)
(ii) inputs of functions e.g z = mean(t)
▸ :
(i) creating a row vector eg. A = 1:5; B = 0:2:10;
(ii) select in a range or all e.g. C= A(1,1:3); D = A(:,:)
(iii) reshape a matrix to a column eg. E = A(:);
Uses of the characters ... ’ ! ∼
▸ ... used to continue the code in the next line
1 if length(a) <5
2 a = [1,2,3,...
3 4,5];
4 end% end for the if condition
▸ ’
(i) to transpose e.g. t =[2,3,4]; s=t’;
(ii) create strings e.g. z = ’Hello’;
▸ ∼ means not e.g. is not equal ∼=
▸ ! same as system
Creation of Arrays
1 % A row vector: use the column seperator
, or space
2 A = [1,2,3,4,5,6];
3
4 % A column vector: use the row seperator ,
;
5 D1 = [2;4;5;6];
6
7 % Matrices of many columns and rows
8 C1 = [2,4,6;2,3,5;1,NaN ,3];
9 C2 =[C1;C1];
Special Matrices
1 % Identity matrix of n by n
2 I = eye (4);
3
4 % Matrix of ones: ones(raws ,columns)
5 D1 = ones (2,5);
6
7 % Matrix of zeros: zeros(raws ,columns)
8 E1 = zeros (5 ,31);
9
10 % n by n magic square matrices
11 M = magic (3);
Matrix Operations
▸ Transpose of A - A’
▸ Inverse of A - inv(A)
▸ multiplication- A*A
▸ element-wise multiplication- A.*A
▸ For a linear equation, Ax = b;
1 x=Ab;
▸ Concatenation
▸ Horz. Concatenation - Number of raws must be the same
Hcon=[A,A] or [A A]
▸ Vert. Concatenation - Number of columns must be the same
Vcon=[A;A]
Matrix Indexing - access a particular element(s) in a matrix.
A = [10 21; 41 51; 32 19];
▸ to access an element
new matrix = A(row index,column index)
eg. A new=A(3,2)
▸ select a number of rows and columns
new matrix = A([row numbers],[column numbers])
eg. B new=A([2 3],[1 2])
▸ deleting a raw or column elements
A([raw numbers],[column numbers])=[]
A(1,:)=[]
Matrix Indexing ...
▸ Replace an element
A(raw index,column index) = new number
eg. A(2,3)=100;
▸ Replace a set of number eg numbers > 5
A(A>5) = new number
eg. A(A>5)=NaN;
▸ finding indices for numbers
index=find(A>5)
A(index)=5
Conditional Statements (if, elseif, else )
▸ if statements, expressions end
eg. doy= 9
if doy < 10
DOY=['00' int2str(doy)];
end
▸ if statements, expressions elseif statements, expressions else
statements, expressions end
if doy<10
DOY=['00' num2str(doy)];
elseif doy>9 && doy<100
DOY=['0' num2str(doy)];
else
DOY=int2str(doy);
end
Conditional statements ... (switch, case, otherwise)
▸ switch switch expression
case case expression
statements, expresions
...
otherwise
statements,expresions
end
eg. igs_station='MBAR'
switch igs station
case 'MBAR'
lon=30.74;lat=-0.6;
case 'EBBE'
lon=32.54;lat=0.04;
otherwise
lon=NaN; lat=NaN;
end
Loops (for and while)
▸ for MATLAB commands end
eg. s= 0; triglenumber=[];
for i1=1:20
s=s+i1;
if mod(s,2)==0
continue
end
triglenumber=[triglenumber;s];
end
while loop
1 z = 'Mbar009 -2000 -12 -13. txt';
2 x = [];
3 i = 1;
4 while isempty(x)
5 pt = z(1:i);
6 x= strfind(pt ,'.');
7 i=i+1;
8
9 end
10 sprintf(pt)
Data Properties
▸ properties of the workspace variables are accessed by
typing whos at command the prompt >>
e.g >> whos
Name Size Bytes Class Attributes
data1 2x3 50 single
data2 100x345 5000 double
data3 1x35 55 cell
data4 12x34 400 char
data5 10x5 58 struc
string - characters enclosed in single quotes.
eg. mytext='Hello world';
▸ Concatenate strings like in Matrices
eg. text=[mytext(1:5) 'my friend'];
▸ convert numeric values to strings - useful in labeling plots
use int2str(numeric value) or num2str(numeric value)
eg. datadir=['/home/andima/data/' int2str(2008) '/Cmn/' ]
▸ Format data into string using sprintf
yr=2008;doy=3
eg. daydir=sprintf('igs/%i/00%i',yr,doy);
Cell Arrays - Each element may point to a scalar, an array, or
another cell array.
eg. C=cell(2, 3)%create 2x3 empty cell array
M = magic(2);
a = 1:3; b = [4;5;6]; s = ’This is a string’;
C{1,1} = M;
C{1,2} = a;
C{2,1} = b;
C{2,2} = s;
▸ Some of the useful functions for cells include
iscell, cell2mat
Structure - good for grouping arrays that are related.
eg. name(1).last = ‘Smith’;name(2).last = ‘Hess’;
name(1).first = ‘Mary’; name(2).first = ‘Robert’;
name(1).sex = ‘female’; name(2).sex = ‘male’;
▸ Alternatively
name = struct(‘last’,Smith’,’Hess’,...,
‘first’,Mary’,’Robert’,‘sex’,female’,’male’);
▸ Related utilities: isstruct, fieldnames, getfield, isfield
File types
▸ script m-files (.m): commands that reside in the base of
workspace
▸ function m-files (.m): memory access controlled;
parameters passed as input, output arguments; reside in
own workspace
▸ mat files (.mat): binary or text files handled with save and
load
▸ mex files (.mex): runs C/FORTRAN codes from m-file;
▸ eng files (.eng): runs m-file from C/FORTRAN code
▸ C codes (.c): generated by MATLAB compiler
▸ P codes (.p): converted m-files to hide source for security
Script m-file
If you have a group of commands that are expected to be
executed repeatedly, it is convenient to save them in a file
▸ enter commands in editor
▸ Save as a *.m file
▸ A script shares the same scope with that which it operates.
Function m-files
▸ It is declared with the key word function, with optional
input parameters on the right and optional output on the
left of = sign
▸ all other parameters within function reside in function’s
own workspace.
▸ created in the MATLAB editor. e.g.
1 function M = my_mean(x)
2 M=sum(x)/numel(x);
3 end
▸ funtions may be called from a script, another function, or
on command line
Importing data into MATLAB
Many functions are available to import data into matlab. The
choice depends on the nature of the data. Some of these
functions include
▸ load:
▸ used to import data without text in it. eg
1 filename = 'mbar034 -2015 -02 -03. txt';
2 Data = load(filename);
reading data using fgetl
▸ fgetl: used to read each line of the data
1 filename = 'mbar002 -2015 -01 -02. Cmn';
fid = fopen(filename);
2 eof = 'Jdatet ';header =[];
3
4 while isempty(header)
5 line1 = fgetl(fid);
6 header = strfind(line1 ,eof);
7 end
reading data using textscan
▸ textscan: used to read each line of the data
1 filename = 'mbar002 -2015 -01 -02. Cmn';
fid = fopen(filename);
2 eof = 'Jdatet ';header =[];
3
4 while isempty(header)
5 line1 = fgetl(fid);
6 header = strfind(line1 ,eof);
7 end
8 Data = textscan(fid);

More Related Content

PDF
Introduction to matlab
PDF
Introduction to matlab
PPTX
intro2matlab-basic knowledge about Matlab.pptx
PDF
3 Data Structure in R
DOCX
Introduction to r
PPTX
ITW 1.pptx
PPT
Introduction to matlab
PPTX
R교육1
Introduction to matlab
Introduction to matlab
intro2matlab-basic knowledge about Matlab.pptx
3 Data Structure in R
Introduction to r
ITW 1.pptx
Introduction to matlab
R교육1

Similar to Basics of programming in matlab for beginners (20)

PPT
PPT
MatlabIntro (1).ppt
PDF
PPTX
presentation.pptx
PPTX
PPT
PDF
La tex basics
PPTX
DOCX
More instructions for the lab write-up1) You are not obli.docx
PPTX
Matlab Tutorial
PPT
MATLAB-Introd.ppt
PDF
Basic R Data Manipulation
PPT
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
PDF
lecture #1 & 2....education....matlab...helpful
PPTX
introduction to matlab.pptx
PPT
Matlab Basic Tutorial
PPT
Matlab Overviiew 2
PPT
Matlab1
PPT
Matlab intro
PPT
MatlabIntro.ppt
MatlabIntro (1).ppt
presentation.pptx
La tex basics
More instructions for the lab write-up1) You are not obli.docx
Matlab Tutorial
MATLAB-Introd.ppt
Basic R Data Manipulation
WIDI ediot autis dongok part 1.ediot lu lemot lu setan lu
lecture #1 & 2....education....matlab...helpful
introduction to matlab.pptx
Matlab Basic Tutorial
Matlab Overviiew 2
Matlab1
Matlab intro
MatlabIntro.ppt
Ad

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Cell Types and Its function , kingdom of life
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Pre independence Education in Inndia.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
Pharma ospi slides which help in ospi learning
PDF
Insiders guide to clinical Medicine.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
TR - Agricultural Crops Production NC III.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
O5-L3 Freight Transport Ops (International) V1.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Cell Types and Its function , kingdom of life
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pre independence Education in Inndia.pdf
Institutional Correction lecture only . . .
Pharma ospi slides which help in ospi learning
Insiders guide to clinical Medicine.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Supply Chain Operations Speaking Notes -ICLT Program
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Microbial disease of the cardiovascular and lymphatic systems
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Basic Mud Logging Guide for educational purpose
TR - Agricultural Crops Production NC III.pdf
Ad

Basics of programming in matlab for beginners

  • 1. Basics of Matlab Programming Opio Phillip Mountains of the Moon University popio@mmu.ac.ug
  • 2. MATLAB:- MATrix LABoratory ▸ Developed by Mathworks, Inc. http://www.mathworks.com ▸ It is an interactive, integrated, environment ▸ for numerical/symbolic, scientific computations and other Apps ▸ shorter program development and debugging time than other languages such as FORTRAN and C ▸ slow compared to FORTRAN or C ▸ easy to use ▸ automatic memory management; no need to declare arrays ▸ etc
  • 3. Getting Started with MATLAB ▸ Windows double click MATLAB icon ▸ Linux Cluster cd to bin folder in the installation dir then ./matlab ▸ Either case it opens a MATLAB window with >> prompt ▸ To stop, type quit or exit at the command prompt >>
  • 4. Current Folder Files in the current folder Work Space a 4 b 6 c 10 Command Window Input Commands at the command line prompt ≫ eg. ≫ a= 4; ≫ b=6; ≫ c=a+b;
  • 5. Variable and File Names ▸ case sensitive, e.g., fname and fName are different names ▸ can be a mix of letters, digits, and underscores (e.g., vector A) ▸ variable namws always start with a letter e.g., xy or x2y ▸ maximum of 63 characters ▸ reserved characters: % = + - ; : ’ [ ] ( ) , # $ & ˆ ! ∼ can NOT be used ▸ No space in the names e.g class marks not allowed
  • 6. Uses of the characters % = ; , ▸ % for adding comments, %% creates a shell in mfile ▸ = to asign a value to a variable e.g c=10 ▸ ; (i) suppresses output in the command window (ii) delimits commands in the same line e.g clear;close all; a=4;b=5; (iii) seperate rows e.g. d=[2;3;4]; ▸ , (i) seperate columns e = [4,2,3,1]; (ii) delimits commands in the same line e.g k = 4,m=12
  • 7. Uses of the characters [] () : ▸ [] (i) for arrays e.g p =[12,3] (ii) delete contents of arrays e.g x = [] deletes contents of x ▸ () (i) matrix indexing e.g t =[2,3,4], s=t(1,2) (ii) inputs of functions e.g z = mean(t) ▸ : (i) creating a row vector eg. A = 1:5; B = 0:2:10; (ii) select in a range or all e.g. C= A(1,1:3); D = A(:,:) (iii) reshape a matrix to a column eg. E = A(:);
  • 8. Uses of the characters ... ’ ! ∼ ▸ ... used to continue the code in the next line 1 if length(a) <5 2 a = [1,2,3,... 3 4,5]; 4 end% end for the if condition ▸ ’ (i) to transpose e.g. t =[2,3,4]; s=t’; (ii) create strings e.g. z = ’Hello’; ▸ ∼ means not e.g. is not equal ∼= ▸ ! same as system
  • 9. Creation of Arrays 1 % A row vector: use the column seperator , or space 2 A = [1,2,3,4,5,6]; 3 4 % A column vector: use the row seperator , ; 5 D1 = [2;4;5;6]; 6 7 % Matrices of many columns and rows 8 C1 = [2,4,6;2,3,5;1,NaN ,3]; 9 C2 =[C1;C1];
  • 10. Special Matrices 1 % Identity matrix of n by n 2 I = eye (4); 3 4 % Matrix of ones: ones(raws ,columns) 5 D1 = ones (2,5); 6 7 % Matrix of zeros: zeros(raws ,columns) 8 E1 = zeros (5 ,31); 9 10 % n by n magic square matrices 11 M = magic (3);
  • 11. Matrix Operations ▸ Transpose of A - A’ ▸ Inverse of A - inv(A) ▸ multiplication- A*A ▸ element-wise multiplication- A.*A ▸ For a linear equation, Ax = b; 1 x=Ab; ▸ Concatenation ▸ Horz. Concatenation - Number of raws must be the same Hcon=[A,A] or [A A] ▸ Vert. Concatenation - Number of columns must be the same Vcon=[A;A]
  • 12. Matrix Indexing - access a particular element(s) in a matrix. A = [10 21; 41 51; 32 19]; ▸ to access an element new matrix = A(row index,column index) eg. A new=A(3,2) ▸ select a number of rows and columns new matrix = A([row numbers],[column numbers]) eg. B new=A([2 3],[1 2]) ▸ deleting a raw or column elements A([raw numbers],[column numbers])=[] A(1,:)=[]
  • 13. Matrix Indexing ... ▸ Replace an element A(raw index,column index) = new number eg. A(2,3)=100; ▸ Replace a set of number eg numbers > 5 A(A>5) = new number eg. A(A>5)=NaN; ▸ finding indices for numbers index=find(A>5) A(index)=5
  • 14. Conditional Statements (if, elseif, else ) ▸ if statements, expressions end eg. doy= 9 if doy < 10 DOY=['00' int2str(doy)]; end ▸ if statements, expressions elseif statements, expressions else statements, expressions end if doy<10 DOY=['00' num2str(doy)]; elseif doy>9 && doy<100 DOY=['0' num2str(doy)]; else DOY=int2str(doy); end
  • 15. Conditional statements ... (switch, case, otherwise) ▸ switch switch expression case case expression statements, expresions ... otherwise statements,expresions end eg. igs_station='MBAR' switch igs station case 'MBAR' lon=30.74;lat=-0.6; case 'EBBE' lon=32.54;lat=0.04; otherwise lon=NaN; lat=NaN; end
  • 16. Loops (for and while) ▸ for MATLAB commands end eg. s= 0; triglenumber=[]; for i1=1:20 s=s+i1; if mod(s,2)==0 continue end triglenumber=[triglenumber;s]; end
  • 17. while loop 1 z = 'Mbar009 -2000 -12 -13. txt'; 2 x = []; 3 i = 1; 4 while isempty(x) 5 pt = z(1:i); 6 x= strfind(pt ,'.'); 7 i=i+1; 8 9 end 10 sprintf(pt)
  • 18. Data Properties ▸ properties of the workspace variables are accessed by typing whos at command the prompt >> e.g >> whos Name Size Bytes Class Attributes data1 2x3 50 single data2 100x345 5000 double data3 1x35 55 cell data4 12x34 400 char data5 10x5 58 struc
  • 19. string - characters enclosed in single quotes. eg. mytext='Hello world'; ▸ Concatenate strings like in Matrices eg. text=[mytext(1:5) 'my friend']; ▸ convert numeric values to strings - useful in labeling plots use int2str(numeric value) or num2str(numeric value) eg. datadir=['/home/andima/data/' int2str(2008) '/Cmn/' ] ▸ Format data into string using sprintf yr=2008;doy=3 eg. daydir=sprintf('igs/%i/00%i',yr,doy);
  • 20. Cell Arrays - Each element may point to a scalar, an array, or another cell array. eg. C=cell(2, 3)%create 2x3 empty cell array M = magic(2); a = 1:3; b = [4;5;6]; s = ’This is a string’; C{1,1} = M; C{1,2} = a; C{2,1} = b; C{2,2} = s; ▸ Some of the useful functions for cells include iscell, cell2mat
  • 21. Structure - good for grouping arrays that are related. eg. name(1).last = ‘Smith’;name(2).last = ‘Hess’; name(1).first = ‘Mary’; name(2).first = ‘Robert’; name(1).sex = ‘female’; name(2).sex = ‘male’; ▸ Alternatively name = struct(‘last’,Smith’,’Hess’,..., ‘first’,Mary’,’Robert’,‘sex’,female’,’male’); ▸ Related utilities: isstruct, fieldnames, getfield, isfield
  • 22. File types ▸ script m-files (.m): commands that reside in the base of workspace ▸ function m-files (.m): memory access controlled; parameters passed as input, output arguments; reside in own workspace ▸ mat files (.mat): binary or text files handled with save and load ▸ mex files (.mex): runs C/FORTRAN codes from m-file; ▸ eng files (.eng): runs m-file from C/FORTRAN code ▸ C codes (.c): generated by MATLAB compiler ▸ P codes (.p): converted m-files to hide source for security
  • 23. Script m-file If you have a group of commands that are expected to be executed repeatedly, it is convenient to save them in a file ▸ enter commands in editor ▸ Save as a *.m file ▸ A script shares the same scope with that which it operates.
  • 24. Function m-files ▸ It is declared with the key word function, with optional input parameters on the right and optional output on the left of = sign ▸ all other parameters within function reside in function’s own workspace. ▸ created in the MATLAB editor. e.g. 1 function M = my_mean(x) 2 M=sum(x)/numel(x); 3 end ▸ funtions may be called from a script, another function, or on command line
  • 25. Importing data into MATLAB Many functions are available to import data into matlab. The choice depends on the nature of the data. Some of these functions include ▸ load: ▸ used to import data without text in it. eg 1 filename = 'mbar034 -2015 -02 -03. txt'; 2 Data = load(filename);
  • 26. reading data using fgetl ▸ fgetl: used to read each line of the data 1 filename = 'mbar002 -2015 -01 -02. Cmn'; fid = fopen(filename); 2 eof = 'Jdatet ';header =[]; 3 4 while isempty(header) 5 line1 = fgetl(fid); 6 header = strfind(line1 ,eof); 7 end
  • 27. reading data using textscan ▸ textscan: used to read each line of the data 1 filename = 'mbar002 -2015 -01 -02. Cmn'; fid = fopen(filename); 2 eof = 'Jdatet ';header =[]; 3 4 while isempty(header) 5 line1 = fgetl(fid); 6 header = strfind(line1 ,eof); 7 end 8 Data = textscan(fid);