Chapter 1
MATLAB Fundamentals
By: Solomon Derbie (Assist. Prof.)
March, 2025
What is MATrix LABoratory (MATLAB)?
▪ It is developed by The 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 traditional
programming languages such as fortran and c.
Automatic memory management; no need to declare arrays.
Easy to use.
Compact notations.
1
Getting Started With MATLAB
▪ Latest version is MATLAB 2024b
▪ For Windows: double click MATLAB icon
▪ For Linux Cluster: katana% matlab
▪ Either case spawns a MATLAB window with >> prompt.
>> % from % to end of line used for code documentation
>> version % this will tell you the running MATLAB version
ans =
9.5.0.944444 (R2018b)
2
Getting Started With MATLAB … Cont’d
▪ >> help % lists available packages/toolboxes on system.
▪ >> help elfun % lists functions in elementary functions package
▪ >> help sin % instructions on the sine function
▪ >> lookfor sine % if you don’t know the function name …
▪ >> doc sin % for full details o f function
▪ >> quit % to quit MATLAB
3
Rules on Variables and File Names
▪ Variable, function, file names
▪ is case sensitive, e.g., NAME and Name are 2 distinct names.
▪ variable begins with a letter, e.g., A2z or a2z
▪ can be a mix of letters, digits, and underscores (e.g., vector_A)
▪ Reserved characters: % = + – ~ ; : ! ' [ ] ( ) , @ # $ & ^
▪ up to 63 characters
▪ A function performs a pre-defined task based on input to yield certain outcome.
4
Rules on Variables and File Names … Cont’d
▪ File name
▪ MATLAB command files should be named with a suffix
of ".m", e.g., myfile.m.
▪ An m-file typically contains a sequence of MATLAB
commands that will be executed in order
▪ A file may contain a collection of commands, functions
▪ Note: To run, enter m-file, without .m, e.g.,
▪ >> myfile
5
Reserved Characters % = ; ,
▪ Some characters are reserved by MATLAB for various purposes.
▪ Some as arithmetic or matrix operators: =, +, - , *, / , \ and others are used to
perform a multitude of operations.
▪ Reserved characters cannot be used in variable or function names.
▪ >> % anything after % until the end of line is treated as comments
▪ >>
6
Reserved Characters % = ; , … Cont’d
▪ >> a = 3 % define a to have the value 3
▪ a=
3
▪ >> a = 3; % “;” suppresses printing
▪ >>
▪ >> b = 4; c = 5; % “;” enables multiple commands on same line
▪ >>
▪ >> d = 6, e = 7; % “,” delimits commands but enables printing
▪ d=
6
7
Reserved Characters : [] ( )
▪ >> x = 1:2:9 % define vector x with : operator (begin:interval:end)
▪ x=
1 3 5 7 9
▪ >> y = 3:5 % interval is defaulted to 1; same as y=[3:5]
▪ y=
3 4 5
▪ >> X = [1, 2, 3; 4, 5, 6] % 2D array. The ; is vertical concatenation.
% [ ] for arrays. Prevents ambiguity
% ; concatenates vertically (new row)
% , concatenates horizontally (new columns)
▪ X=
1 2 3
4 5 6 8
Reserved Characters … and '
▪ >> x = [1 2 3 … % elipses … means to be continued on the next line
4 5 6]
▪x=
1 2 3 4 5 6
▪ >> s = 'this is a character string'; % blanks preserved within quotes
▪ >> x = [1 2 3]' % ' performs transpose (e.g., turns row into column)
▪x=
1
2
3
9
Reserved Characters … and '
▪ >> X = [1 2 3; 4 5 6]; size(X) % figure out the size (dimensions) of X
▪ ans =
2 3
▪ >> X = [1 2 3; 4 5 6]; numel(X) % total number of entries in X
▪ ans =
10
Array Operations
>> a = 1:3; % a is a row vector
>> b = 4:6; % b is a row vector
>> c = a + b % c has same shape as a & b
c=
5 7 9
>> A = [a;b] % combines rows to generate 2x3 matrix A;
A=a;b ?
A=
1 2 3
4 5 6
11
Array Operations … Cont’d
>> B = A' % B is transpose of A
B=
1 4
2 5
3 6
Other ways to create B ? (hint: with a and b )
12
Matrix Operations
>> C = A*B % * is overloaded as matrix multiply operator
C=
14 32
32 77
>> D = A.*A % a .* turns matrix multiply to elemental multiply
D=
1 4 9
16 25 36
13
Matrix Operations … Cont’d
>> E = A./A % elemental divide
E=
1 1 1
1 1 1
>> who % list existing variables in workspace
Your variables are:
A B C D E a b d
14
For Loops
for j=1:5 % use for-loops to execute iterations / repetitions
for i=1:3
a(i, j) = i + j ;
end
end
▪ Utilities to initialize or define arrays: ones, rand, eye, . . .
▪ Trigonometric and hyperbolic functions : sin, cos, sqrt, exp, . . .
▪ These utilities can be used on scalar or vector inputs
>> a = sqrt(5); v = [1 2 3]; A = sqrt(v);
15
if Conditional
Scalar operation . . .
a = zeros(3); b = zeros(3);
for j=1:3
for i=1:3
a(i,j) = rand; % use rand to generate a random number
if a(i,j) > 0.5
b(i,j) = 1;
end
end
end
Equivalent vector operations . . .
A = rand(3); % A is a 3x3 random number double array
B = zeros(3); % Initialize B as a 3x3 array of zeroes
B(A > 0.5) = 1; % set to 1 all elements of B for which A > 0.5
16
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.
▪ >> edit mytrig.m % enter commands in editor window
▪ a=sin(x); % compute sine x (radians)
▪ b=cos(x); % compute cosine x (radians)
▪ disp( [‘a =‘ num2str(a) ] ) % prints a; here, [ . . . ] constitutes a string array
▪ disp( [‘b = ‘ num2str(b) ] ) % prints b
17
Script m-file … Cont’d
Select File/Save to save it as mytrig.m.
A script shares the same scope with that which it operates. For
example, if it runs from the matlab
Define x, then use it in mytrig.m:
>> x=30*pi/180; % converts 30 degrees to radians
>> mytrig % x is accessible to mytrig.m; share same workspace
a = 0.5000
b = 0.8660
18
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 =.
▪ All other parameters within function reside in function’s own workspace.
▪ Use MATLAB editor to create file: >> edit average.m
▪ function avg=average(x)
▪ % function avg=average(x)
▪ % Computes the average of x
▪ %x (input) matrix for which an average is sought
19
Function m-files … Cont’d
▪ % avg (output) the average of x
▪ avg = sum(x)/numel(x); % the average
▪ end
▪ Save the above with File/Save
▪ Recommendation: saves file with name same as function name.
▪ It may be called from a script, another function, or on command line:
▪ >> a = average(1:3) % a = (1 + 2 + 3) / 3
▪ a=
2
▪ >> help average % prints contiguous lines with % in average
20
Script or Function m-file ?
Scripts
▪ Pros:
▪ Convenient; script’s variables are in same workspace as caller’s.
▪ Cons:
▪ Slow; script commands loaded and interpreted each time it is used.
▪ Risks of variable name conflict inside and outside of script.
21
Script or Function m-file ? … Cont’d
▪ Functions
▪ Pros:
▪ Scope of function’s variables is confined to within function. No worry for
name conflict with those outside of function.
▪ What comes in and goes out are tightly controlled which helps when debugging
becomes necessary.
▪ Compiled the first time it is used; runs faster subsequent times.
▪ Easily be deployed in another project.
▪ Auto cleaning of temporary variables.
22
Script or Function m-file ? … Cont’d
▪ Cons:
▪ I/O are highly regulated, if the function requires many pre-defined variables, it
is cumbersome to pass in and out of the function – a script m-file is more
convenient.
23
Some Frequently Used Functions
>> magic(n) % creates a special n x n matrix; handy for testing
>> zeros(n,m) % creates n x m matrix of zeroes (0)
>> ones(n,m) % creates n x m matrix of ones (1)
>> rand(n,m) % creates n x m matrix of random numbers
>> repmat(a,n,m) % replicates a by n rows and m columns
>> diag(M) % extracts the diagonals of a matrix M
>> help elmat % list all elementary matrix operations ( or elfun)
>> abs(x); % absolute value of x
24
Some Frequently Used Functions … Cont’d
>> exp(x); % e to the x-th power
>> fix(x); % rounds x to integer towards 0
>> log10(x); % common logarithm of x to the base 10
>> rem(x,y); % remainder of x/y
>> mod(x, y); % modulus after division – unsigned rem
>> sqrt(x); % square root of x
>> sin(x); % sine of x; x in radians
>> acoth(x) % inversion hyperbolic cotangent of x 25
MATLAB Graphics
▪ Line plot
▪ Bar graph
▪ Surface plot
▪ 2D, 3D visualization tools as well as other graphics are available in MATLAB
software.
26
Line Plot
>> t = 0:pi/100:2*pi;
>> y = sin(t);
>> plot(t,y)
27
Line Plot … Cont’d
>> xlabel(‘t’);
>> ylabel(‘sin(t)’);
>> title(‘The plot of t vs sin(t)’);
28
Line Plot … Cont’d
>> y2 = sin(t-0.25);
>> y3 = sin(t+0.25);
>> plot(t,y,t,y2,t,y3)
% make 2D line plot of 3 curves
>> legend('sin(t)','sin(t-0.25)','sin(t+0.25',1)
29
2D Bar Graph
>> x = magic(3); % generate data
for bar graph
>> bar(x) % create bar chart
>> grid % add grid for
clarity
30
Surface Plot
>> Z = peaks; % generate data for plot; peaks returns function values
>> surf(Z) % surface plot of Z
Try these commands also:
>> shading flat
>> shading interp
>> shading faceted
>> grid off
>> axis off
>> colorbar
>> colormap(‘winter’)
>> colormap(‘jet’)
31
Thank You!