Matlab Chapter 1
Matlab Chapter 1
>> ans =
34 34 34 34
When you do not specify an output variable, MATLAB uses the
variable ans, short for answer, to store the results of a calculation.
Variable is the name given to the region in memory. Variable does
not require any type declarations or dimension statements.
Rules for writing variable names:
1. first character must be letter, others can be letters, numbers
and underscore(_) character, only first 63 characters are
significant.
1) + addition
2) − subtraction
3) * multiplication
4) ^ power
A
5) ' conjugate transpose
6) \ Left division
7) / right division
ans =
2 3
>> length(a)
ans =
3
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^ Element-by-element power
.' Unconjugated array transpose
>> u = [ 10 -11 12]; w = [2 1 3];
2.7778
66.4444
76.7778
>> x2=A\b
x2 =
2.7778
66.4444
76.7778
How to solve this by right division?
2.7778
66.4444
76.7778
To place labels on X-axis & Y-axis and to give title to the above
generated graph, use the commands xlabel(), ylabel() and title()
receptively.
Script File :
Instead of typing a series of commands directly in a
command window, this group of commands can be placed into a
file. This file containing commands can then be executed by
typing its name in command window. This file is called as script
file or M-file (since it has a file extension “.m”).
Example 4. Temperature conversion program, which accepts
temperature in Fahrenheit as input through keyboard, converts it
into degree Celsius and outputs the result to screen in a formatted
way.
Displays a string in the command window and waits for the user to
type in a response. When user types in and presses Enter, that is
stored in the variable on the left.
Specifier Description
%c Single character
%d Decimal notation (signed)
%e Exponential notation (using a lowercase e as in 3.1415e+00)
%E Exponential notation (using an uppercase E as in 3.1415E+00)
%f Fixed-point notation
%g The more compact of %e or %f, as defined in [2]. Insignificant
zeros do not print.
%G Same as %g, but using an uppercase E
%o Octal notation (unsigned)
%s String of characters
%u Decimal notation (unsigned)
%x Hexadecimal notation (using lowercase letters a-f)
%X Hexadecimal notation (using uppercase letters A-F)
Escape Characters
This table lists the escape character sequences you use to specify non-
printing characters in a format specification.
Description
Character
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\\ Backslash
\‘ ‘ or ‘ ‘ (two single quotes) Single quotation mark
%% Percent character
Complex Arithmetic:
z=3+4i
real(z)
imag(z)
conj(z)
abs(z)
angle(z)
Program: Plot frequency response of RC low pass filter (R=6kΩ, C=1μF)
R=16e3;C=1e-6;%Initalization
f=1:2:1000;%create array of input frequencies
res=1./(1+j*2*pi*f*R*C);%calculate response
mag=abs(res);%Magnitude response
ph=angle(res);%Phase response
%Plotting frequency response
subplot(211);
loglog(f,mag);
title('Amplitude response');
xlabel('frequency(Hz)');
ylabel('output/input ratio');
grid on;
subplot(212);
semilogx(f,ph);
title('Phase response');
xlabel('frequency(Hz)');
ylabel('output-input phase');
grid on;
Special Matrices:
% ones:
% load X with a 3x3 matrix full of ones
X=ones(3,3)
% rand:
% load Y with a 4x6 matrix full of random numbers between 0 and
1
% The random numbers are uniformly distributed on [0,1]
Y=rand(4,6)
Example 5: subplot function
Source code:
%plotting function and its derivative
x=0:pi/20:2*pi;
y1=sin(2*x);
y2=2*cos(2*x);
plot(x,y1,'r--',x,y1,'b*',x,y2);
xlabel('x');
ylabel('y');
title('Plot of f(x)=sin(2x) and its derivative');
grid on;
Program 7. Write MATLAB script file that returns the equivalent
resistance of series combination of R1, R2 and R3 where R1 =
100 Ω, R2 = 90 Ω, R3 = 10 Ω.
*************************************************
The equivalent resistance is =
200 Ohms
*************************************************
MATLAB file types
function[x,y]=draw_circle(r);
%a function file to draw a circle of radius r
theta=linspace(0,2*pi,100);
x=r*cos(theta);
y=r*sin(theta); body of a
plot(x,y); function
axis('equal');%to set the scale of both axes same
title(['Circle of radius ',num2str(r)]);
Function syntax:
function[x,y]=draw_circle(r);
1. Function file begins with a function definition line. (If this line is
absent, file is script file).
2. File name should be same as name of function.
How to execute a function?
If function definition line is:
function[x,y]=draw_circle(r);
This function can be called by:
[x1 y1] = draw_circle(r1)
draw_circle(5)
Comparison
%Purely inductive circuit; voltage and current waveforms
%Initialization
V=230; %supply voltage;
f=50; %supply frequency in Hz;
L=20e-3; %Inductance;
no_cycles=2; %number of cycles for plot
delta_t=1e-3; %time increment
%Computation
Vm=sqrt(2)*V; %Voltage amplitude
w=2*pi*f; %supply frequency in rad/s
XL=w*L; %Inductive reactance
T=1/f; %Time period of waveforms
t=0:delta_t:no_cycles*T; %time vector for plot
v=Vm*sin(w*t); %Equation for supply voltage
iL=(Vm/XL)*sin(w*t-pi/2); %Equation for current through L
%Plotting
plot(t,v,t,iL);grid;
xlabel('Time(s)'); ylabel('v(V) and iL(A)');
title('voltage and current waveforms in purely inductive circuit');
gtext('v');gtext('iL');
where „variable' is the name of the variable to which handle of the function is
assigned.
'var1', 'var2', etc. are a comma separated list of arguments of the function,
'expression' is a single mathematical expression involving those variables.
The expression can include any built-in or user-defined functions.
>>a = sqr(5)
a=
25
ans =
4 9
>> F=inline('x.^2');
>> F(5)
ans =
25
Do the same thing at the command line if you want the base workspace to
access the variable.
The global declaration must occur before the variable is actually used in a
function.
Although it is not required, using capital letters for the names of global variables
helps distinguish them from other variables.
>>A = [ 1 2 3 ; 4 5 6 ; 7 8 0 ];
>>b = [ 366 ; 804 ; 551 ];
The values of x1, x2 and x3 can be found out using
>>x = inv (A) * b
or
>>x=A\b