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);
Ad

Recommended

intro2matlab-basic knowledge about Matlab.pptx
intro2matlab-basic knowledge about Matlab.pptx
uf5221985
 
matlab_tutorial.ppt
matlab_tutorial.ppt
SudhirNayak43
 
matlab_tutorial.ppt
matlab_tutorial.ppt
KrishnaChaitanya139768
 
matlab_tutorial.ppt
matlab_tutorial.ppt
ManasaChevula1
 
matlab tutorial with separate function description and handson learning
matlab tutorial with separate function description and handson learning
vishalkumarpandey12
 
Introduction to matlab
Introduction to matlab
vikrammutneja1
 
MATLAB for Engineers ME1006 (1 for beginer).pptx
MATLAB for Engineers ME1006 (1 for beginer).pptx
lav8bell
 
Matlab Tutorial.ppt
Matlab Tutorial.ppt
RaviMuthamala1
 
Lecture 01 variables scripts and operations
Lecture 01 variables scripts and operations
Smee Kaem Chann
 
Tutorial 2
Tutorial 2
Mohamed Yaser
 
Matlab practical and lab session
Matlab practical and lab session
Dr. Krishna Mohbey
 
Matlab introduction
Matlab introduction
Satish Gummadi
 
Matlab Manual
Matlab Manual
Thesis Scientist Private Limited
 
Matlab basics
Matlab basics
TrivediUrvi2
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Introduction to matlab
Introduction to matlab
Mohan Raj
 
Matlab Introduction for beginners_i .ppt
Matlab Introduction for beginners_i .ppt
DrSeemaBHegde1
 
Matlab_Introduction_by_Michael_Medvinsky.ppt
Matlab_Introduction_by_Michael_Medvinsky.ppt
khaliq1
 
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
divyapriya balasubramani
 
Introduction to programming in MATLAB
Introduction to programming in MATLAB
mustafa_92
 
Matlab guide
Matlab guide
aibad ahmed
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
Matlab anilkumar
Matlab anilkumar
THEMASTERBLASTERSVID
 
matlab Lesson 1
matlab Lesson 1
Vinnu Vinay
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 

More Related Content

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

Lecture 01 variables scripts and operations
Lecture 01 variables scripts and operations
Smee Kaem Chann
 
Tutorial 2
Tutorial 2
Mohamed Yaser
 
Matlab practical and lab session
Matlab practical and lab session
Dr. Krishna Mohbey
 
Matlab introduction
Matlab introduction
Satish Gummadi
 
Matlab Manual
Matlab Manual
Thesis Scientist Private Limited
 
Matlab basics
Matlab basics
TrivediUrvi2
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Introduction to matlab
Introduction to matlab
Mohan Raj
 
Matlab Introduction for beginners_i .ppt
Matlab Introduction for beginners_i .ppt
DrSeemaBHegde1
 
Matlab_Introduction_by_Michael_Medvinsky.ppt
Matlab_Introduction_by_Michael_Medvinsky.ppt
khaliq1
 
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
divyapriya balasubramani
 
Introduction to programming in MATLAB
Introduction to programming in MATLAB
mustafa_92
 
Matlab guide
Matlab guide
aibad ahmed
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
Matlab anilkumar
Matlab anilkumar
THEMASTERBLASTERSVID
 
matlab Lesson 1
matlab Lesson 1
Vinnu Vinay
 
Lecture 01 variables scripts and operations
Lecture 01 variables scripts and operations
Smee Kaem Chann
 
Matlab practical and lab session
Matlab practical and lab session
Dr. Krishna Mohbey
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
Murshida ck
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
Dr. Manjunatha. P
 
Introduction to matlab
Introduction to matlab
Mohan Raj
 
Matlab Introduction for beginners_i .ppt
Matlab Introduction for beginners_i .ppt
DrSeemaBHegde1
 
Matlab_Introduction_by_Michael_Medvinsky.ppt
Matlab_Introduction_by_Michael_Medvinsky.ppt
khaliq1
 
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
divyapriya balasubramani
 
Introduction to programming in MATLAB
Introduction to programming in MATLAB
mustafa_92
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
Vijay Kumar Gupta
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
Mukesh Kumar
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
MahuaPal6
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 

Recently uploaded (20)

A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Gladiolous Cultivation practices by AKL.pdf
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
NSUMD_M1 Library Orientation_June 11, 2025.pptx
NSUMD_M1 Library Orientation_June 11, 2025.pptx
Julie Sarpy
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
LDMMIA Yoga S10 Free Workshop Grad Level
LDMMIA Yoga S10 Free Workshop Grad Level
LDM & Mia eStudios
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
Ad

Basics of programming in matlab for beginners

  • 1. Basics of Matlab Programming Opio Phillip Mountains of the Moon University [email protected]
  • 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);