Professional Documents
Culture Documents
Lecture # 6
MATLAB Basics
Basic commands.
Declaring & manipulating variables.
Plotting graphs.
Introducing Variables
.* element-by-element multiplication
./ element-by-element division
.^element-by-element power
“%” is the neglect sign for Matlab (equaivalent of “//” in C).
Anything after it on the same line is neglected by Matlab
compiler.
Sometimes slowing down the pause %wait until any key
execution is done deliberately pause(3) %wait 3 seconds
for observation purposes. You
can use the command “pause”
for this purpose
Strings
MATLAB also can accept and manipulate
string variables.
A string is defined by enclosing it in single
quotes.
Example: aString = ‘Hello World!’
To convert a string to
lowercase or uppercase, 1
use the following commands.
1. Change string in matrix A to
lowercase:
B = lower(A)
2. Change string in matrix A to
2
uppercase:
B = upper(A)
Concatenate Strings
Concatenating string means merging two or
more strings together.
To concatenate strings, use the strcat
command.
Example:
to concatenate
str1 and str2:
newStr = strcat(str1,str2)
Replace String
To replace part of the
string with a new
value, use the strrep
command.
Example: replace the
word ‘study’ with the
word ‘read’ in the
string str1.
strrep(str1,’study’,’r
ead’)
Plot
MATLAB supports many types of graph
and surface plots:
x = 0:pi/36:10*pi
y = sin(x)
plot(x,y,‘m')
Plot Styles
Example: Plotting the lines
using various line parameters
clear, close all
clc
xxx = 1:100
yyy = rand(1,100)
plot(xxx,yyy)
figure, plot(xxx,yyy,'g:')
figure, plot(xxx,yyy,'r--')%
figure, plot(xxx,yyy,':mo')
plot(xxx,yyy,'r')
hold on
plot(aaa,bbb,'-.gv')
hold off
Subplots
Subplots
x=0:0.1:2*pi;
subplot(2,2,1);
plot(x, sin(x));
subplot(2,2,2);
plot(x, cos(x));
subplot(2,2,3)
plot(x, exp(-x));
subplot(2,2,4);
plot(peaks);
Drawing Different Types of Graphs
clear, close all
clc
x = 0:pi/36:2*pi
y = cos(x)
bar(x,y,'b')
Title
>>title(‘This is the sinus function’)
x axis label
>>xlabel(‘x (secs)’)
y axis label
>>ylabel(‘sin(x)’)
Legend
>> legend ('string1','string2',...)
Display Facilities
x = -pi: pi/20: pi;
plot(x,cos(x),'-ro',
x, sin(x),'-.b')
legend('cos_x','sin_x');
x = -pi:pi/20:pi;
>> plot(x,cos(x),'-
ro',x,sin(x),'-.b')
>> hold on
>> ylabel('cos_x, sin_x');
>> hold on
>> xlabel('pi');
>> title('Plot')
>> legend('cos_x', 'sin_x')
log-log Plot
x = 0:10^2;
>> y = exp(x);
>> loglog(x,y,'-s')
Semi log Plot
x = 0:1000;
y = log(x);
figure
semilogx (x,y)
3D Plot
k = 5;
n = 2^k-1;
[x,y,z] = sphere(n);
>> surf(x,y,z)
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure
mesh(Z)