matlab basics program

Post on 23-Apr-2017

240 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

MATLAB WORKSHOP MATERIAL

SESSION 1 – MATLAB BASICS

PROGRAM:1. OPERATIONS WITH VARIABLES

The code for assigning values to the variables>> a=12a =12>> B=4B =4>> C=(a-B)+40-a/B*10C =

18The above code is repeated using semicolon

>> a=12;>> B=4;>> C=(a-B)+40-a/B*10;>> CC =

18The above assignment operations are done in the same line as follows:

>> a=12, B=4; C=(a-B)+40-a/B*10a =12C =

18

2. NAMING AND CHECKING EXISTENCE(i) The who command displays the list of the variables currently in the memory.

>> a=12; B=4; C=a+B;>> whoYour variables are:B C a

(ii) The whos command displays the list of the variables currently in the memory and their size together.

>> whos Name Size Bytes Class Attributes B 1x1 8 double C 1x1 8 double a 1x1 8 double

3. CLEARING OPERATIONS The clear command 1. The clear variable_name command removes the specified variables from the memory

>> clear a>> whoYour variables are:B C

2. The clear command removes all variables from the memory>> clear >> who>>

DATA AND DATA FLOW IN MATLAB

1. MATRIX OPERATIONS & OPERATORS (i) Creating Matrix Variables

The code to create a 3 x 4 matrix:>> MAT=[3 11 6 5; 4 7 10 2; 13 9 0 8]MAT =

3 11 6 5 4 7 10 213 9 0 8

The code to assign a new value to the (3,1) element:>> MAT(3,1)=20MAT =

3 11 6 5 4 7 10 220 9 0 8

The code to use elements in a mathematical expression:>> MAT(2,4)-MAT(1,2)ans =

-9

(ii) The colon (:) Operator The code to define a matrix A with 5 rows and 6 columns:

>> A=[1 3 5 7 9 11; 2 4 6 8 10 12; 3 6 9 12 15 18; 4 8 12 16 20 24; 5 10 15 20 25 30]A =

1 3 5 7 9 112 4 6 8 10 123 6 9 12 15 184 8 12 16 20 245 10 15 20 25 30

The code to define a column vector B from the elements in all of the rows of column 3 in matrix A.

>> B=A(:,3)B =

5691215

The code to define a row vector C from the elements in all of the columns of row 2 in matrix A.

>> C=A(2,:)C =

2 4 6 8 10 12The code to define a matrix E from the elements in rows 2 through 4 and allthe columns in matrix A.

>> E=A(2:4,:)E =

2 4 6 8 10 123 6 9 12 15 184 8 12 16 20 24

The code to define a matrix F from the elements in rows 1 through 3 and columns 2 through 4 in matrix A.

>> F=A(1:3,2:4)F =

3 5 74 6 86 9 12

>>

(iii) Adding Elements to a MatrixThe code to define a 2 x 4 matrix E:

>> E=[1 2 3 4; 5 6 7 8]E =

1 2 3 45 6 7 8

The code to add the vector 10 14 18 22 to the third row of E:>> E(3,:)=[10:4:22]E =

1 2 3 4 5 6 7 810 14 18 22

The code to define a 3 x 3 matrix K:>> K=eye(3)K =

1 0 00 1 00 0 1

The code to append matrix K to matrix E. The numbers of rows in E and K must be the same.

>> G=[E K]G =

1 2 3 4 1 0 0 5 6 7 8 0 1 010 14 18 22 0 0 1

(iv) Deleting Elements in a MatrixThe code to define a vector kt with 10 elements:

>> kt=[2 8 40 65 3 55 23 15 75 80]kt =

2 8 40 65 3 55 23 15 75 80The code to eliminate 6th element in the vector kt:

>> kt(6)=[]kt =

2 8 40 65 3 23 15 75 80The code to eliminate elements 3 through 6 in the vector kt:

>> kt(3:6)=[]kt =

2 8 15 75 80The code to define a 3 x 5 matrix mtr:

>> mtr=[5 78 4 24 9; 4 0 36 60 12; 56 13 5 89 3]mtr =

5 78 4 24 9 4 0 36 60 1256 13 5 89 3

The code to eliminate all the rows of column 2 through 4 in the vector mtr:>> mtr(:,2:4)=[]mtr =

5 9 4 1256 3

>>

2. RESHAPING MATRICES The code to create a 2 x 3 matrix A:

>> A=[5 1 6; 8 0 2]A =

5 1 68 0 2

The code to create a 3 x 2 matrix B from the elements of matrix A using reshape() built-in function:

>> B = reshape(A,3,2)B =

5 08 61 2

3. ARRAYS (i) Addition and Subtraction

The code to create two vectors VectA and VectB and code to create another vector VectC by adding VectA and VectB:

VectA=[8 5 4]; VectB=[10 2 7];>> VectC=VectA+VectBVectC =

18 7 11The code to create two 2 x 3 matrix A and B:

>> A=[5 -3 8; 9 2 10]A =

5 -3 89 2 10

>> B=[10 7 4; -11 15 1]B =

10 7 4-11 15 1

The code to subtract matrix B from the matrix A:>> A-Bans =

-5 -10 420 -13 9

The code to create a matrix C by adding matrixes A and B:>> C=A+BC =

15 4 12-2 17 11

>>

(ii) MultiplicationThe code to create two matrixes A and B:

>> A=[1 4 2; 5 7 3; 9 1 6; 4 2 8]A =

1 4 25 7 39 1 6

4 2 8>> B=[6 1; 2 5; 7 3]B =

6 12 57 3

The code to multiply matrix A by matrix B and assign the result to the variable C:

>> C=A*BC =

28 2765 4998 3284 38

EDITING AND DEBUGGING M FILES

PROGRAM:

1. Program in a script file that converts a quantity of energy (work) given in units of either joule, ft-lb, cal, or eV to the equivalent quantity in different units specified by the user. The program asks the user to enter the quantity of energy, its current units, and the desired new units. The output is the quantity of energy in the new units.

The conversion factors are: 1 J = 0.738 ft-lb = 0.239 cal = 6.24 × 1018 eV. Use the program to:

(a) Convert 150 J to ft-lb.(b) Convert 2,800 cal to J.(c) Convert 2.7 eV to cal.

%This programs converts the unit of energy %from one format to another formatclcEin=input('Enter the value of the energy (work) to be converted: ');EinUnits=input('Enter the current units (J, ft-lb, cal, or eV): ','s');EoutUnits=input('Enter the new units

(J, ft-lb, cal, or eV): ','s');

error=0;switch EinUnits case 'J' EJ=Ein; case 'ft-lb'

EJ=Ein/0.738; case 'cal' EJ=Ein/0.239; case 'eV' EJ=Ein/6.24e18; otherwise error=1;end

switch EoutUnits case 'J' Eout=EJ; case 'ft-lb' Eout=EJ*0.738; case 'cal' Eout=EJ*0.239; case 'eV' Eout=EJ*6.24e18; otherwise error=1;end

if error disp('ERROR current or new units are typed incorrectly.')else fprintf('E = %g %s \n',Eout,EoutUnits)end

2. A program in a script file that creates an n x m matrix with elements that have the following values. The value of each element in the first row is the number of the column. The value of each element in the first column is the number of the row. The rest of the elements each has a value equal to the sum of the element above it and the element to the left. When executed, the program asks the user to enter values for n and m.

%Creating a matrix with a loop

n=input('Enter the number of rows ');m=input('Enter the number of columns ');A=[];for k=1:n

for h=1:mif k==1

A(k,h)=h;elseif h==1

A(k,h)=k;

elseA(k,h)=A(k,h-1)+A(k-1,h);

endend

end

3. Six singers—John, Mary, Tracy, Mike, Katie, and David—are performing in a competition. Write a MATLAB program that generates a list of a random order in which the singers will perform.

%Creating a random listclc;clear all;close all;n=6;L(1)=randi(n);for p=2:n

L(p)=randi(n);r=0;while r==0

r=1;for k=1:p-1

if L(k)==L(p)L(p)=randi(n);r=0;break

endend

endendfor i=1:n

switch L(i)case 1

disp('John')case 2

disp('Mary')case 3

disp('Tracy')case 4

disp('Mike')case 5

disp('Katie')case 6

disp('David')end

end

4. Program to find the greatest of two numbers using greater than operator

%This program is used to verify the operatorsa= input('\n Enter the Value for A : ');b= input('\nEnter the Value for B : ');for s=a:2:b fprintf('\ns = %g',s);endif a>b fprintf('\nA is greater\n');else fprintf('\nB is greater\n');end

5. Program to print the Fibonacci series

%Fibonacci Numbersk=0;l=1;fprintf('\n%g %g ',k, l);for s=1:1:20 r=k+l; fprintf('%g ', r); k=l; l=r;end

6. Program to calculate the average marks of a student

%This script file calculates the average marks of a studentdisp(' STUDENT DETAILS ');name = input('Enter Name ', 's');rno = input('Enter Roll Number ','s');M1 = input('Enter Mark1 ');M2 = input('Enter Mark2 ');M3 = input('Enter Mark3 ');M4 = input('Enter Mark4 ');M5 = input('Enter Mark5 ');total = M1+M2+M3+M4+M5;avg=total/5;disp(' ');disp(' MARK LIST ');fprintf('\nName : %s',name);

fprintf('\nRno : %s',rno);fprintf('\nTotal : %f',total);fprintf('\nAverage: %f\n',avg);

7. Program to print lines with different formats

%Line commandx=[-2:0.01:4];y=3*x.^3-26*x+6;yd=9*x.^2-26;ydd=18*x;line(x,y,'LineStyle','-','color','b')line(x,yd,'LineStyle','--','color','r')line(x,ydd,'linestyle',':','color','k')

Result:

8. Program to display three graphs using the plot command

%This program plots three graphs a=[-2:0.01:4];%y=3*x.^3-26*x+6;x=[-1:0.1:1];y=[1:0.1:3];yd=9*a.^2-26;ydd=18*a;plot(x,y,'-b',a,yd,'--r',a,ydd,':k')

Result:

9. Program to draw the light intensity using the plot command

%plots the light indensity as a function of disracnex=[10:0.1:22];y=95000./x.^2;xd=[10:2:22];yd=[950 640 460 340 250 180 140];plot(x,y,'-','LineWidth',1.0)xlabel('DISTANCE (cm)')ylabel('INTENSITY (lux)')title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)axis([8 24 0 1200])text(14,700,'Comparison between theory and experiment.','EdgeColor','r','LineWidth',2)hold onplot(xd,yd,'ro--','linewidth',1.0,'markersize',10)legend('Theory','Experiment',0)hold off

Result:

10.Program to display basic signals and to explain the subplot functions %This Program exaplains the subplot function

%Unit Step Signalsn = input('Enter the n Value : ');t = 0:1:n-1;y = ones(1,n);subplot(3,2,1);plot(t,y);%stem(t,y);ylabel('Aplitude -->');xlabel('a(n) -->');title('Unit Step Signals');hold on; %Unit Ramp Signalsn = input('Enter the length of the ramp sequence : ');t = 0:n;subplot(3,2,2);plot(t,t);%stem(t,t);ylabel('Aplitude -->');xlabel('a(n) -->');title('Unit ramp Signal'); %Impulse Signalt = -2:1:2;y = [zeros(1,2), ones(1,1), zeros(1,2)];subplot(3,2,3);plot(t,y);%stem(t,y);ylabel('Aplitude -->');xlabel('a(n) -->');title('Unit impulse Signals');%Sine Signalt = 0:.1:pi;y = sin(2*pi*t);subplot(3,2,4);plot(t,y);%stem(t,y);ylabel('Aplitude -->');xlabel('a(n) -->');title('Unit Sine Signals');

%Cosine Signalt = 0:.1:pi;y = cos(2*pi*t);subplot(3,2,5);plot(t,y);%stem(t,y);ylabel('Aplitude -->');xlabel('a(n) -->');title('Unit Cosine Signals');hold off;

Result:

11.Program With Special Graphics%Vertical Bar Plotyr=[1988:1994];sle=[8 12 20 22 18 24 27];bar(yr,sle,'r')xlabel('Year')ylabel('Sales (Millions)')Result:

%Horizontal Bar Plotyr=[1988:1994];sle=[8 12 20 22 18 24 27];barh(yr,sle)xlabel('Sales (Millions)')ylabel('Year')

Result:

%Stairs Plot and Stem plotyr=[1988:1994];sle=[8 12 20 22 18 24 27];stairs(yr,sle)subplot(2,1)stem(yr,sle)subplot(2,2)Result:

%pie plotgrd=[11 18 26 9 5];pie(grd)title('Class Grades')

Result:

12. Mesh and Surface Plots

%Mesh Plotx=-3:0.25:3;y=-3:0.25:3;[X,Y] = meshgrid(x,y);Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);mesh(X,Y,Z)xlabel('x'); ylabel('y')zlabel('z')Result:

%Surface Plotx=-3:0.25:3;y=-3:0.25:3;[X,Y]=meshgrid(x,y);Z=1.8.^(-1.5*sqrt(X.^2+Y.^2)).*cos(0.5*Y).*sin(X);surf(X,Y,Z)xlabel('x'); ylabel('y')zlabel('z')Result:

top related