MATLAB Review
MATLAB Review
• MATrix LABoratory
• Developed by The Mathworks, Inc (http://www.mathworks.com)
• Interactive, integrated, environment
– for numerical computations
– for symbolic computations
– for scientific visualizations
• It is a high-level programming language
Characteristics of MATLAB
>> lookfor date % search for keywords that best describe the function
>> Ctrl+C % stop Matlab from running
>> clc % clear screen
Special characters
Coulmn separator:
Row separator: Semicolon (;)
space/coma (,)
Creating sequences:
• From : jump: till
• linespec(X1, X2, N)
generates N points between
X1 and X2.
Creating Matrices
>> B=A(3,1);
>> A(:,end)=[1;7;3;8;4];
• The row number is first, followed by the column number.
Linear Algebra Operations
Matrix Multiplication
>>a.*b
>>a.*b’
>>a*b’
String Arrays
my_num=input('insert a number');
% now calculate the square root of the number and print
it out:
square_root = sqrt(my_num)
Running Scripts
• >> square_root_script
• The header - comments you place at the beginning of your scripts will be
returned to users when they get help for your script.
• >> help square_root_script
• Note: The variables defined in the script remain in the workspace even
after the script finishes running.
• Creating comments: ctrl+r, or right click on the mouse, or
%{
coment
coment
%}
Running Scripts (2)
• Find and Replace – ctrl+F
• Key words
• Indenting: Ctrl+I
Flow Control Constructs
• Logic Control:
– IF / ELSEIF / ELSE
– SWITCH / CASE / OTHERWISE
• Iterative Loops:
– FOR
– WHILE
The if, elseif and else statements
• Works on Conditional statements
• Logic condition is ‘true’ if its different then 0.
if I == J if I == J
A(I,J) = 2; A(I,J) = 2;
else if abs(I-J) == 1 elseif abs(I-J) == 1
A(I,J) = -1; A(I,J) = -1;
else
else
A(I,J) = 0;
A(I,J) = 0;
end
end %else if
end %if
N=10;
for I = 1:2:N
for J = 1:N
A(I,J) = 1/(I+J-1);
end
end
The while loop
• xlabel('x-axis'); ylabel('y-axis'); 1
2
3
• title('Comparing Exponential Functions'); 2 4
y-axis
1
0.5
0
-10 -5 0 5 10
Subplots
Subplot (2,2,1)
More about figures
0.5
y
-0.5
-1
1 1.5 2 2.5 3 3.5 4 4.5 5
• Y=sin(x)
• Z=log(x)
• Put your name in the title
• Hint: check the doc on function “LineSpec”.
Solution
• x=1:0.05:5;
• y=sin(x);
• z=log(x);
• hold on
• plot (x,y,'-.r*')
• plot (x,z,'-.go')
• hold off
• title ('Merav''s graph');
• xlabel ('x')
• ylabel ('y')
• legend ('sin(x)', 'log(x)');
More exercise
• Make a 3 three-dimensional graph of (x,y,z) – use Matlab help.
• Make two separate 2-D graphs, with separate axis, in the same
window: y vs. x, and z vs. x.
• Use the same x,y,z as defined in the previous exercise
3D graph
sin(x) log(x)
1 1.8
0.8 1.6
2
0.6
1.4
0.4 1.5
1.2
0.2
1
1
z
y=sin(x)
0
z
0.8 0.5
-0.2
0.6
-0.4 0
0.4 1
-0.6
0.5 5
0.2 0 4
-0.8
3
-0.5 2
-1 0
1 2 3 4 5 1 2 3 4 5 y -1 1
x
x x
Solution