Final MATLAB (1) (1) - 1
Final MATLAB (1) (1) - 1
The prompt >> is displayed in the Commas tell MATLAB to display results;
command window and when the semicolonssuppress printing.
command window is active, a blinking
To continue expressions or commands
cursor should appear on the right side
onto additional lines, we use … in
of the prompt.
succession. Comment lines and variable
Simple Computations can be performed names cannot be split between two
by typing the command and pressing lines.
enter.
MATLAB processing can be interrupted
at any moment by pressing Ctrl+C.
COMPLEX NUMBERS Note: Can handle specialized mathematical
functions Bessel, Legendre, Beta function
No special handling for complex etc.
numbers.
NUMBER DISPLAY FORMATS
By default,
% Complex numbers
if a result is an integer, it is displayed as
c1=1-2i % the appended i signifies
an integer.
the imaginary part
SIMPLE ARRAY
% Mathematical functions
x=sqrt(2) %gives square root of 2
y=rem(23,4) % remainder function, Start with a left bracket, enter the
23/4 has remainder 3 desired values separated by spaces (or
commas) and then close it using a right
y_deg=30; %degree to be converted to
radians
bracket.
y_rad=y_deg*pi/180;
y1=sin(y_rad) Colon notation
x=first:increment:last
Try yourself:
linspace command
(2+6*i)/(9*i)*(1+i)
x=linspace (first, last, n)
MATHEMATICAL FUNCTIONS
Note: These arrays have one row and multiple
sqrt, sin, cos, sinh, asin, acos, exp, log
columns.
etc.
a) assign the first row of A to a vector
% ARRAY CONSTRUCTION called x1
b) assign the last 2 rows of A to an
% Method 1. array called y
x=[0, 0.1*pi,0.2*pi,0.3*pi, c) compute the sum over the
0.4*pi,0.5*pi,0.6*pi,0.7*pi,0.8*p columns of A
i,0.9*pi,pi]
y=sin(x)
COLUMN VECTORS
% ARRAY INDEXING
Specify it element by element and
x(3) % gives 3rd element of the
array separate values with semicolons.
%Transpose of A
A’ transpose of matrix B=A'
%A^-1
inv(A) inverse of matrix invA=inv(A)
%Determinant of A
chol(A) cholesky decomposition of a detA=det(A)
positive definite matrix A
det(A) determinant of matrix %Rank of A
rank(A)
T=cputime;
[L,U]=lu(A) LU decomposition
Operations….
[Q,R]=qr(A) QR decomposition
TT=cputime-T;
for k = 2:1000
if, elseif, else, end
x(k) = x(k-1) + 5;
if(condition #1)
end
statement #1
Change the first line to preallocate a 1-by-1000
elseif(condition #2)
block of memory for x initialized to zero.
statement #2
This time there is no need to repeatedly
else reallocate memory and move data as more
statement #3 values are assigned to x in the loop:
for k = 2:1000
Try yourself:
x(k) = x(k-1) + 5;
Given x = 1:10 and y = [3 1 5 6 8 2 9 4 7 0],
execute and interpret the results of the following end
commands:
1. x( (x < 2) | (x >= 8) ) VECTORIZATION
2. y( (x < 2) | (x >= 8) )
3. x(y < 0). One way to make your MATLAB programs run
faster is to vectorize the algorithmsyou use in
constructing the programs.
PREALLOCATING ARRAYS
A simple example involves creating a table of
for and while loops that incrementally increase logarithms.
the size of a data structure each time through
x=0.01;
the loop can adversely affect performance and
memory use. Repeatedly resizing arrays often for k = 1:1001
requires that MATLAB spend extra time looking
y(k) = log10(x);
for larger contiguous blocks of memory and
then moving the array into those blocks. You x = x + .01;
can often improve on code execution time by
end
preallocatingthe maximum amount of space
that would be required for the array ahead of A vectorized version of the same code is:
time.The following code creates a scalar
variable x, and then gradually increases the size x = .01:.01:10;
of x in a for loop instead of preallocating the y = log10(x);
required amount of memory at the start:
% Loops and logical statements % A loop free version-vectorization is
as follows:
%for loop %--------------------------------------
%----------- k=1:10;
A=sin(k)'*cos(k);
%Compute the first 6 terms of the
Fibonacci sequence %while loop
%-------------
%f_i=f_{i-1} + f_{i-2}
%echo on f(1)=0; f(2)=1; k=3;
f(1)=0; f(2)=1; while k <=6
for i=[3 4 5 6] %for i=3:6 f(k)=f(k-1)+f(k-2);
f(i)=f(i-2)+f(i-1); k=k+1;
end end
break % if / else if
%--------------------
% Ex 2 for for loop % Roots of the polynomial ax^2+bx+c
%-------------------- a=input('Enter value of a =');
% Generating sine function for 11 evenly b=input('Enter value of b =');
placed points c=input('Enter value of c =');
Try yourself: k = 0;
for n=1:3:10
Calculate distance between x =(1,4) and y=(5,9). n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
PLOTTING TOOLS (2D) k = k+1;
subplot(2,2,k)
Plot(x,y,’r’) co-ordinates x-y, colour-red plot(x,y,'r')
title(sprintf('Graph %g. Plot based
axis([ a,b,c,d]) dimension of the box holding the plot upon n = %g points.'...
[a b c d]=[xmin xmax ymin ymax] , k, n10))
xlabel('x')
xlabel(‘ ’) label x axis ylabel('y')
axis([-2,2,-.8,.8])
ylabel(‘ ’) label y axis grid
pause(3);
legend(‘ ’) distinguish various curves in same end
plot
grid adds grid lines to graph Try Yourself:
pause( ) holds on to current graph till you Plot y = sin x, 0<x<pi taking 100 linearly spaced
press enter points in the given interval.
Pause(n) holds on to current graph for n
seconds
% Graphs of two ellipses in the same subplot creates an array of plots in same window
%figure
loglog plot using log-log scales
% x(t) = 3 + 6cos(t), y(t) = -2 +9sin(t)
% x(t) = 7 + 2cos(t), y(t) = 8 +6sin(t) semilogx plot using log scale on the x-axis
% There are several commands to enhance
semilogy plot using log scale on the y-axis
the readability of the graph.
legend('ellipse1', 'ellipse2')
xlabel('x')
ILLUSTRATION OF MESH GRID:
h = get(gca,'xlabel');
%gca= get current axis; the axis targetted
%here is x-axis. % Illustration of meshgrid
x=-1:0.05:1;
set(h,'FontSize',12) y=x;
set(gca,'XTick',-4:10) [xiyi]=meshgrid(x,y);
% Specify font size and tick marking along zi=yi.^2-xi.^2;
the current axis. mesh(xi,yi,zi)
axisoff
ylabel('y') % To plot the graph of the mesh surface
h = get(gca,'ylabel'); along with contour plot beneath the
set(h,'FontSize',20) % plotted surface:
set(gca,'YTick',-12:2:14) meshc(xi,yi,zi)
title('Graphs of (x-3)^2/36+(y+2)^2/81 = 1
and (x-7)^2/4+(y-8)^2/36 = 1.')
h = get(gca,'Title');
set(h,'FontSize',12)
grid
POLYNOMIALS Try yourself:
Imp=H*sum(fmp)
Try yourself:
Try yourself:
Solve using Gauss Quadrature formula
Solve using composite midpoint quadrature ∫
formula: