Introduction To MATLAB: Prepared By: Mahendra Shukla
Introduction To MATLAB: Prepared By: Mahendra Shukla
Development Environment
MATLAB language
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
Variables
No need for types. i.e.,
int a;
double b;
float c;
All variables are created with double precision unless
specified and they are matrices.
Example:
>>x=5;
>>x1=2;
Matrix:
Vector : >> A=[1 2; 3 4];
>> a=[1 2 3]; >> A'
>> a' ans =
1 1 3
2 2 4
3
Creating Vectors
A = [ x y]
1 2 4 5
B = [x ; y]
1 2
4 5
Matrix operations
^: exponentiation
*: multiplication
/: division
\: left division. The operation A\B is
effectively the same as INV(A)*B,
although left division is calculated
differently and is much quicker.
+: addition
-: subtraction
Array Operations
Evaluated element by element
.' : array transpose (non-conjugated transpose)
.^ : array power
.* : array multiplication
./ : array division
plot(xdata, ydata,
‘marker_style’);
For example: Gives:
>> x=-5:0.1:5;
>> sqr=x.^2;
>> pl1=plot(x, sqr, 'r:s');
Graphics - Overlay Plots
cos(n/4)
1
>> n=-10:10;
>> f=stem(n,cos(n*pi/4)) 0.5
>> title('cos(n\pi/4)')
>> xlabel('n') 0
-0.5
-1
-10 -5 0 5 10
n
subplots
Cosine Sine
1 1
-1 -1
0 5 10 0 5 10
Save plots
Use saveas(h,'filename.ext')
to save a figure to a file.
Useful extension types:
bmp: Windows bitmap
>> f=figure;
emf: Enhanced metafile
>> x=-5:0.1:5;
eps: EPS Level 1
>> h=plot(x,cos(2*x+pi/3));
fig: MATLAB figure
>> title('Figure 1');
jpg: JPEG image
>> xlabel('x');
m: MATLAB M-file
>> saveas(h,'figure1.fig')
tif: TIFF image, compressed
>> saveas(h,'figure1.eps')
Sine Wave in Matlab
t = [ 0 : 1 : 40 ]; % Time Samples
f = 500; % Input Signal Frequency
fs = 8000; % Sampling Frequency
x = sin(2*pi*f/fs*t); % Generate Sine
Wave
figure(1);
stem(t,x,'r'); % View the samples
figure(2);
stem(t*1/fs*1000,x,'r'); % View the
samples
hold on;
plot(t*1/fs*1000,x); % Plot Sine Wave
Practice Problems
Plot the following signals in linear scale
x(t ) sin( 3t ) 5 t 5
y (t ) e 2t 3 0t 5
Plot the real part and imaginary part of the following signal
x(t ) e0.5t j (t / 3) 0 t 10
For the signal in previous question, plot its phase and magnitude