Introduction to Matlab Programming
Topics:
• Command line and script/function
• Matlab help/ doc
• Variables, string, array, multidimensional array/ vector/matrix
-special functions:
size(), length(), linspace()
end-> as variable, closing statement
• Control flow of code: conditional statements (if/elseif/else)
• Loop (while/for)
• Functions
• plot(x,y)
User defined function needs to be in current
folder
Current directory
All the variables in use
• • •
Command prompt
Command prompt for quick verification/ monitoring variables
Most of the time we will use Editor, save Programs as ‘.m’ file
Name of Matlab file/ variable can not start with numbers or special character
(e.g. 1_is_not_a_valid_name)
• A character array is a sequence of characters, just as a numeric array is a sequence of numbers. Defined within quotes: ‘this is a string’
string_var=’Hello World’ % string variable
Open the file: while_loop_break_ctr_c.m
• Give the poor computer a break! Press ctl+c already!
• display(‘is an useful function to ’)
• Comments can not only make a code more readable, they are handy for debugging code
Variable name in Matlab
• Matlab is case-sensitive Value assignment in Matlab
• Don’t have to worry about int/float/double in Matlab
_sin_of_48_
my_sin_in_degree
sin
1st_var
A=5; a=1; A A=a; A
Open the file: matrix_variable.m, my_sin_in_degree.m
• Variable scope
Array/vector/matrix
• All Matlab variables are multidimensional arrays, no matter what type of data
• Square brackets [] are used for Array construction
• Parentheses () are used for Operator precedence, Function argument
enclosure, and Array indexing
p=[1,2,3; 4,5,6] % elements in a row are separated with comma (,) or space q=[1 2 3; 4 5 6] % rows are separated with a semicolon
r=[1 2 3 4 5 6]
s=[1 2 3 …
4 5 6]
m=[1 2 3]
% line break creates a new row
% continue a statement to the next line using ellipsis (…)
% row matrix
n=[1 2 3]’% the ? operator transpose a matrix , results in a column matrix here
Open the file: matrix_const.m
Array/matrix indexing
Array/matrix indexing
• Matlab array/vector indexing starts with 1 unlike other programming language where index of 1st element is 0.
%% indexing
x=[1,2,3; 4,5,6] % elements in a row are separated with comma (,) or space
% x(0) % ERROR! Array/matrix indexing starts with 1 in Matlab, not 0 like some other language x2=x(2)
x5=x(5)
x2_2=x(2,2) % is equivalent to x(5), but it’s a good practice to use row and column index x3_end=x(3:end)
%%
a=[5 1+7];
b=[a(2) 7 a; x(3:end)] b12_12=b(1:2,1:2) b_row_1=b(1,:) % row 1 b_col_3=b(:,3) % column 3
• •
x = j:k creates a unit-spaced vector x with elements [j,j+1,j+2,…,k]
x = j:i:k creates a regularly-spaced vector x using i as the increment between elements. The vector elements are roughly equal to [j,j+i,j+2*i,…,j+m*i], where usually j+m*i=k
Creating large/useful array
• •
•
•
% first_value: increment :last_value
y = linspace(x1,x2) returns a row vector of 100 evenly spaced points between x1 and x2.
angles=(1/100:1/100:1)*pi;
y = linspace(x1,x2,n) generates n points. The spacing between the points is (x2-x1)/(n-1). linspace() is similar to the colon operator, “:”, but gives direct control over the number of points and always includes the endpoints.
y = logspace(a,b) generates a row vector y of 50 logarithmically spaced points between decades 10^a and 10^b. The logspace function is especially useful for creating frequency vectors. The function is the logarithmic equivalent of linspace and the ‘:’ operator.
y = logspace(a,b,n) generates n points between decades 10^a and 10^b.
%% first_value: increment :last_value
angles_1=(1/100:1/100:1)*pi; angles_2=(pi/100:pi/100:pi); angles_3=linspace(pi/100,pi); angles_4=linspace(pi/100,pi,100);
xx=5:10 % default value of ‘increment’ is 1 yy=10:-2:2 % negative increment
• press up arrow (↑) key with the cursor in the command prompt to access previous commands
Useful initialization functions
a=zeros(2) % 2×2 matrix with all zero(0) elements b=zeros(2,3) % 2×3 matrix
var_c=[1 2; 3 4; 5 6]
dim_of_var_c=size(var_c) % [#row_of_var_c #column_of_var_c]=[3 2] e=zeros(size(var_c)) % zeros(3,2)
z=[zeros(4,1) ones(4,1) zeros(1,4)’]
Open the file: useful_matrix_function.m
• length() is useful in loop control condition
z=[zeros(4,1) ones(4,1) zeros(1,4)’]
size_of_z=size(z)
length_of_z=length(z)% returns number of rows, each row is considered an element
M = max(A) returns the maximum elements of an array.
•If A is a vector, then max(A) returns the maximum of A.
•If A is a matrix, then max(A) is a row vector containing the maximum value of each column.
%%
var_d=[2 4; 9 6; 8 9]
[r8 c8]=find(var_d==8)
find_8=find(var_d==8) % returns the row number [r9 c9]=find(var_d==9) % returns index of all 9s
%%
[value_max index_max]=max(var_d) %need smarter programming to find the proper index
• sind(), cosd(), tand() takes variable in degrees
• asind(), acosd(), atand() returns value in degrees
Open the file: complex_number.m
sqrt(-2)
var1=40i
var2=40j
if var2==var1
display(‘you can use either “i” or “j” to represent imaginary number’);
else
display(‘Matlab is treating “i” and “j” are different!!!’) end
var3= 4+5j
% var4= 6+j7 % error
var6=6+1j*6
% [r6 i6]=[real(var6) imag(var6)] % error, can not assign variables this way
r6=real(var6)
i6=imag(var6)
angle(var6)*180/pi atan(imag(var6)/real(var6))*180/pi sqrt(real(var6)^2+i6^2) magnitude6=abs(var6)
abs(-6) % absolute value
Dot operator
a=[6 4 2] % array b=2 % scaler
a_by_b=a/b % array divided by a scaler a_times_b=a*b % array multiplied by a scaler c=[3 2 2] % array
a_by_c=a/c % I don’t know what it does
% a_times_c=a*c % dimension error
a_dot_by_c=a./c % element by element division a_dot_by_c1=[a(1)/c(1) a(2)/c(2) a(3)/c(3)] a_dot_times_by_c=a.*c % element by element division a_dot_times__c1=[a(1)*c(1) a(2)*c(2) a(3)*c(3)]
• We will revisit dot operator in lab 2
Reference: http://math.boisestate.edu/~calhoun/teaching/matlab-tutorials/lab_31/html/lab_31.html
file: dot_opt.m
• Due to roundoff errors during computer calculations, two theoretically equal numbers can differ slightly, causing an equality or inequality test to fail.
a=0; b=sin(pi);
display(‘a==b’) a==b
display(‘abs(a-b)<1e-14') abs(a-b)<1e-14
display('4>=4′) 4>=4
Open the file: control_flow.m
Control flow: if / else / elseif
Control flow: if / else / elseif
a=0; b=sin(pi);
if a==b
display(‘”a” and “b” are equal’) % rounding error with ‘pi’
else
display(‘”a” and “b” are not equal’) % rounding error with ‘pi’
display(‘lets try to be more specific’) end
%%
if ~(a>b) & ~(b>a) % ‘a’ is not greater than ‘b’ “and” vice versa
display(‘”a” and “b” are equal’) % rounding error with ‘pi’ elseif a>b
display(‘”a” is grater than “b”‘) else
display(‘”b” is grater than “a” ‘) % rounding error with ‘pi’ end
Loop (for/while)
%% loop
condition_var=10;
loop_count=0;
while condition_var>3
condition_var=condition_var-2
loop_count=loop_count+1
end
%%
loop_count=0;
for condition_var=10:-2:3
condition_var
loop_count=loop_count+1
end
%%
condition_var=10:-2:3
for ii=1:length(condition_var)
ii display(‘condition_var(ii)’) condition_var(ii)
new_var1(ii)=condition_var(ii)^2;
end
new_var1
new_var2=condition_var.^2 % Matrix operation in faster than loops
Function
• A function is a special type of m-file that runs in its own independent workspace
• A function is saved as a m-file with the same exact name of the function as
function_name.m in the current working directory.
function [outarg1,outarg2, …]= function_name(inarg1,inarg,…) …
(Executable code)
…
end
function [z1, z2] = add_sub(x,y) if x>y
z1 = x + y;
z2 = x – y;
else
z1 = x – y;
z2 = x + y;
end end
file: add_sub.m
2d plot
index of the array ‘y’
close all
clear all
Clc
x=1:5:360;
a=sind(x);
b=cosd(x);
plot(x,a);
hold on
plot(x,b);
xlabel(‘x’); legend(‘sin(x)’,’cos(x)’);
for ii=1:length(x)
[s1(ii) s2(ii)]=
add_sub(a(ii),b(ii));
end
figure (3)
subplot(211)
plot(x,s1);
xlabel(‘x’);
ylabel(‘s1’)
subplot(212)
plot(x,s2);
xlabel(‘x’);
ylabel(‘s2’)
file: plot_example.m