What is Matlab?
Matlab stands for ________ __________.
Lecture 1:
Introduction to Matlab Programming Matlab is a programming language
optimized for linear algebra operations.
Math 490
Prof. Todd Wittman It is very useful for numerical computation
The Citadel and is commonly used by mathematicians
and engineers in academia and industry.
Basic Arithmetic Variables
If we type a calculation, when we press ENTER the
result appears as ans. To assign a value to a variable, just type it. We
2+3 don't need to declare variables first: x=2
ans = Matlab is weakly typed, which means the
5 variable type is flexible.
Pressing the up arrow repeats the last input. x=2 x=2.3 x=2+4i x='hello'
In addition to basic + - * / there are basic mathematical To see what variables are available, look in the
functions
Workspace window or type: who
exp(2) sin(pi) asin(2)
To delete a variable x: clear x
There may be round-off errors.
Watch out for the values Inf and NaN. If you see these If you type just clear, all variables will be
values, then you probably ______________________. deleted.
Vectors Appending Vectors
We enclose vector values in square brackets. We can append one vector onto another by enclosing
v = [2 3 4 5 6] them in brackets, separated by commas.
We can look up a value at a position: v(2) v = [1:5, 10, 2:2:16]
The colon operator takes on a range of values This trick also works for strings.
v = 2:6 s = [‘pokemon’, ’rule!’]
More generally we set start:step:end (default step=1)
Ex Make a vector of all multiples of 3 less than 1000. This is particularly useful when we want to combine
strings and numbers.
w = _____:_____:_____ We can convert a number to a string using the command
num2str. (Or go the other way with str2num.)
What is the last entry in w? _________ disp(['The value of x is ', num2str(x)])
1
Matrices Matrix Operations
To make a 2D matrix, the semi-colon skips to the next row: Matrix multiplication: A*B A^3
A = [2 3 4; 5 6 7] Component-wise operations: A.*B A.^3
We look up values by row,column: A(2,3) = 7;
Inverse: inv(A)
You can look up a submatrix with the colon: A(1:2,2:3)
Using just a colon gets all possible values: A(:,2:3)
Transpose: A'
Special matrices Look up matrix size: size(A)
rand(10,20) eye(3) zeros(4,5) ones(3,2) Eignenvalues: [v,d] = eig(A);
Linear solver Ax=b: x = linsolve(A,b);
As matrices get large, you can suppress output with a Vectorize a matrix: A(:)
semi-colon at the end.
R = rand(20,20);
Change matrix size: reshape(A,[r,c]);
Linear Algebra Pop Quiz Basic Flow Control
Suppose we make a matrix: A=[1 2; 3 4]; while i > 0 if x >0
Write what each command below does. ... ...
end elseif x<0
A'= A(:) = ...
for i = 1:10 else
... ...
A^2 = A.^2 = end end
An Odd Example Basic Plotting
The plot function takes two vectors as input. The first vector goes
The function mod(a,b) tells the remainder after a is on the horizontal axis (x) and the second on the vertical (y).
Ex Plot a sine wave on 0,2.
divided by b.
x=0:0.1:2*pi;
So a is multiple of b if mod(a,b)=____.
y=sin(x);
plot(x,y,'r')
for i = 1:100 axis([0,2*pi,-1,1])
if mod(i,2) == 0 title('A sine wave')
disp([num2str(i), ' is even.']); You can suprress the axis numbers with: axis off
Note the axis command sets the x and y bounds:
else
axis( [ xmin, xmax, ymin, ymax ] )
disp([num2str(i), ' is odd.']);
You can reset the axis and tick marks manually too.
end; You can (and should) add text to the plot:
end; title xlabel ylabel gtext legend
2
Label Label Label Plotting on Common Axis
I will deduct points if you do not label your The hold command tell Matlab to plot things on top of
each other, rather than erasing the previous picture.
plot axes or title your images.
hold on forces all subsequent plots to appear on top of
the last plot.
hold off releases the plot, so any new plots will erase the
current picture. 1
0.8
x=0:0.01:2*pi; 0.6
0.4
plot(x,sin(x),'r'); 0.2
hold on; -0.2
-0.4
plot(x,cos(x),'b'); -0.6
-0.8
hold off -1
0 1 2 3 4 5 6 7
Subplots Subplots
The subplot command divides the figure into windows.
subplot(TotalNumRows, TotalNumCols, index) x=0:0.1:2*pi;
The index goes from left to right, top to bottom (raster subplot(1,2,1); plot(x,sin(x));
order).
Which box would subplot(2,3,4) get?
subplot(1,2,2); plot(x,cos(x));
x=0:0.1:2*pi;
subplot(2,1,1); plot(x,sin(x));
Pro Tip: If the numbers are all single digits, we can omit subplot(2,1,2); plot(x,cos(x));
the commas: subplot(234)
Subplot Example Subplot Example
Ex Plot the graphs of sin (
) on −, for N=1 to 10.
x = -pi:0.1:pi;
for i = _______________________________
subplot( ___________ , ___________ , ___________ );
plot( ______________________________________
title( ______________________________________
end
3
Navigation Saving & Loading Data
You can change directories by clicking the You can save your current variables to a
little folder icon at the top. Matlab save file (.mat file).
save my_data x y z
You will see the file my_data.mat appear
in the current folder.
You can quit Matlab, come back a couple
days later, and load the variables x,y,z to
Check current position: pwd the workspace.
Print all files in the current folder: ls load my_data
Reading & Writing Images Grayscale Images
A grayscale image is given by a 2D matrix with the low
Load images into a matrix with imread. value being black, the high value being white, and
everything in between denoting a shade of gray.
A = imread('mypic.jpg'); Typically, optical images are 8-bit images which take on
Write a matrix to an image with imwrite. integer values in the range [0,255]. (0=black, 255=white)
The top left corner of the image is position (1,1).
You need to specify the image format. I
Note Matlab records matrix position as (row,col), so it's
like to use bitmaps to avoid compression (y,x) with the y values inverted.
artifacts.
A(1,1)=255;
imwrite(A, 'mypic.bmp', 'bmp'); A(1,2)=0;
A(2,1)=100;
A(2,2)=200;
Displaying Images imagesc vs. imshow
You can display a matrix with the command imagesc. The imagesc command fills the window with the image, ignoring the
Matlab defaults to an annoying red-blue "jet" colormap. So we need to tell aspect ratio.
Matlab to use a grayscale display by typing: colormap gray It draws grayscale images from min=black to max=white.
Often we prefer not to display the axis numbers on images: axis off
If you want to see how the image would appear like in a web
imagesc(A); imagesc(A); imagesc(A); browser with proper aspect ratio and in 8-bit format, use the imshow
colormap gray; colormap gray; command.
axis off; A(1,1)=10; A(1,2)=6; A(2,1)=8; A(2,2)=11; A(3,1)=7; A(3,1)=9;
4
imagesc vs. imshow Data Format
The difference between imagesc and imshow is most Images typically come in 8-bit uint8 format.
obvious when the length and width of the image are very But we can't do math on the images in this format.
different. So we cast to double before we do our arithmetic tricks.
A = double(A);
Then when we're done, we cast back to 8-bit image
format.
A = uint8(A);
Some Matlab functions require 8-bit images as input,
others prefer double images.
Image Arithmetic Writing Scripts
To brighten a grayscale image A by 60%, we multiply all A Matlab script is a set of commands that you
values by 1.6. can save as .m file.
A = 1.6 * A;
Select Script from the New dropdown menu.
But multiplying an integer by 1.6 does not necessarily
give an integer in the range [0,255].
To preserve image formats, we need to cast to double
and then back to integer 8-bit.
A = double(A);
A = 1.6 * A;
A = uint8(A);
To see the effect of brightening an image, you really Ex Display a 8x8 chessboard where each
should use the imshow command, not imagesc. (Why?) square is 10x10 pixels.
Writing Functions Chessboard Function
We can create user-defined functions that Matlab can function [ A ] = chessboard ( N )
% Return image of NxN chessboard.
call. We call these functions or m-files. % Each square on the chessboard is 10x10 pixels.
The first line is: for i=1:N
if mod(i,2)==0
function [out1, out2] = function_name (in1, in2) color=0;
Comments start with a % sign. Matlab will ignore these else
lines, but they are helpful for people who read your code color=255;
end;
later. Matlab highlights comment lines in green. for j=1:N
A(1+10*(i-1):10*i, 1+10*(j-1):10*j)=color;
color = 255-color;
Ex Write a function that returns the image of a × end;
chessboard. end;
A = uint8(A);
5
Binary Images Binary Images
A binary image is black or white, no shades of gray. We can mask out part of an image by doing component-wise
A binary image typically has values of just 0 (black) or 1 (white). multiplication by a binary image.
Binary images are useful for detection tasks, e.g. identify if each A = imread('cat.jpg'); A = double(A);
pixel belongs to a cat. These types of images are often referred to D = zeros(size(B)); D(120:160,50:250)=1;
as a mask.
subplot(131); imagesc(A);
subplot(132); imagesc(D);
subplot(133); imagesc(D.*A);
Color Images Color Images
A standard color image has 3 channels indicating the
intensity of Red, Green, and Blue light (RGB). We can access an individual color channel by the 3rd
dimension.
A color image is a 3D matrix, with the 3rd dimension
representing color. A = imread('ash.png');
Think of a color image as being a stack of 3 grayscale subplot(141); imshow(A); title('Original');
images. subplot(142); imshow(A(:,:,1)); title('Red');
subplot(143); imshow(A(:,:,2)); title('Green');
A=imread('ash.png'); subplot(144); imshow(A(:,:,3)); title('Blue');
size(A)
ans =
708 1129 3
Color Images Color Image Example
Each pixel in a color image is a 3D vector. B=
Black = (0,0,0)
White = (255,255,255)
Start with a red background.
Red = (255,0,0)
Green = (0,255,0)
Blue = (0,0,255) B(1:3,1:5,1)=_____; B(1:3,1:5,2)=_____; B(1:3,1:5,3)=_____;
Now make the white pixel.
The color of a pixel is determined by the mixture of the RGB values.
B(1,2,1)=_____; B(1,2,2)=_____; B(1,2,3)=_____;
Finally make the purple pixel.
B(2,4,1)=_____; B(2,4,2)=_____; B(2,4,3)=_____;
6
Color Image Example 2 Color Image Example 2
h = _______________; % Height of flag.
Ex Make the flag of Japan.
w = round(3*h/2); % Width of flag.
d = round(3/5 * h); % Diameter of circle
A(1:h,1:w,1:3) = _____________; %Start with white background.
for i = 1:h
for j = 1:w
if _____________________________________________
A(i,j,2)=0; A(i,j,3)=0;
end;
end
end
A = uint8(A);
imshow(A);
Color Image Example 2 Processing Color Images
In this course, we mostly deal with how to process grayscale
images.
Suppose you have a Matlab function that processes a grayscale
image.
To process a color image, you just need to run your function 3 times.
If you look closely at the circle we produced, you for i = 1:3
may see the edges are not smooth. New_A(:,:,i) = MY_FUNCTION ( A(:,:,i) );
This phenomenon of having "blocky" or end
"staircased" edges is called _______________.
You can turn a 3-channel color image into 1-channel grayscale
image using rgb2gray.
How can we remove it?
Matrix Operations Averaging 3 Bands
Bad Answer Better Answer
In Matlab, we want to avoid loops and function [A] = average(B) function [A] = average(B)
B = double(B); B = double(B);
make use of matrix operations to make it [m,n,k] = size(B); A = (B(:,:,1)+B(:,:,2)+B(:,:,3)) / 3;
run faster. for i=1:m
for j=1:n
A(i,j) = (B(i,j,1)+B(i,j,2)+B(i,j,3)) / 3;
Ex Write a function that returns the end;
Best Answer
end;
average of the color bands. function [A] = average(B)
Note: This is a crude way to turn a color image B = double(B);
into grayscale. The Matlab command rgb2gray A = mean(B,3);
actually does a weighted average.