3 views

Uploaded by Chaubey Ajay

Mat lab code for Function and Array

Mat lab code for Function and Array

© All Rights Reserved

- JSBSimCUJ
- Week5 Homework
- Circuit Design With VHDL-Problem Solutions.pdf
- Lab C++ 08 - Arrays
- Week5-Homework.pdf
- Test Bank Ninth Edition
- Chinmoy Mukherjee-Cracking the Coding Interview_ 60 Java Programming Questions and Answers (Volume 1)-CreateSpace Independent Publishing Platform (2015)
- ff
- MATLAB Statistics Assignment
- Intro to R Lecture 1
- 207 full
- Mat Lab Tutorial 5
- Mat Lab Plotting 2
- Assignment Mod 10
- Arrays
- Memory Diagram Guide
- practical
- Computer Science
- Voyager Scripting
- ingles proyeccto.docx

You are on page 1of 4

Vectors

A vector is a one-dimensional array of numbers. A row vector is written horizontally; a column vector is

written vertically.

In Matlab, vectors are defined by writing the components inside square brackets. For row vectors, the

elements are separated by commas or spaces, e.g. [5 3 -2 4 -1 0 2]. The components in column vectors

are separated by semicolons, e.g. [3;-1;0;2;9].

We can refer to a component of a vector by putting the component number in round brackets. For example,

if v is the vector [5 0 2 -4 1 0 3], then v(5) is the 5th component which is 1.

Matrices

A matrix is a two-dimensional array of numbers. We write these in Matlab inside square brackets, entering

one (horizontal) row at a time, just like a row vector, and we put a semi-colon at the end of each row. For

example, the matrix

2 5 1

C=

1 0 4

is entered into Matlab using C=[-2 5 1;1 0 4].

We can refer to a single row or column of a matrix. To find the second row of matrix C, we write C(2,:),

which gives [1 0 4]. It finds all the components in C whose first subscript is 2. Similarly the third column

of C is referred to as C(:,3).

for loops

These are used to repeat sections of code when the number of repeats is known before the code is run.

Examples include:

Do 5 iterations. We know in advance that the section will be repeated 5 times.

x=3;

for i=1:5

x=(x+2/x)/2;

disp(x)

end

Subtract the first row of a matrix from the second row - assume the matrix has n columns. When

this is performed, the value for n will be known - though it wont be known when the code is written.

A=[1 5 3 5; 6 4 -2 5;6 0 -5 2];

[m,n]=size(A)

for i=1:n

A(2,i)=A(2,i)-A(1,i);

end

disp(A)

while loops

These are used to repeat sections of code when the number of repeats depends on the results found/calculated

in the loop.

Examples include:

Prompt the user to input a positive integer and keep prompting until they do.

n=input(Enter a positive number );

while n<=0

n=input(Enter a positive number );

end

The number of repeats depends on how long it takes the user to enter a positive number.

Perform iterations until the result is less than 1.

x=input(Enter the value of x );

m=0.8;

while x>=1

x=x*m;

disp(x)

end

In this case we keep multiplying by m until x becomes less than 1. The number of repeats depends

on how many times we need to do this to get below 1.

Functions

Functions are also used to repeat sections of code. They may be used for standard methods that we want

to use often. A function is usually defined by writing it in a separate Matlab file.

A function will be of the form

function output parameter(s) = function name ( input parameter(s) )

% Write in here some comments about what the function does

Matlab statements to calculate the output parameters values from the input parameter values.

The output parameters represent the values that you want calculated in the function; the input parameters

represent the values that are available to the function. If there is more than one output parameter, the

output parameters are written in square brackets.

For example, we could write a Matlab function to find the volume and surface area of a cylinder with

given height and diameter. The information used is the diameter and the height, so these will be the

input parameters. The values to be calculated are the volume and surface area; these will be the output

parameters.

function [vol,area]=mycylinder(d,h)

% calculates the volume (vol) and surface area (area) of

% cylinder whose diameter is d and height h

r=d/2;

vol=pi*r^2*h;

area=2*pi*r^2+2*pi*r*h;

To use the function in a script file or in the Command Window, we give the variable names for the results

in the output parameters, and the values (or variables containing them) in the input parameters. For

example to find the volume and surface area of a cylinder whose diameter is 4 and height 5, we would

write

[v,a]=mycylinder(4,5)

If the diameter and height of the cylinder we are interested in are contained in variables diam and ht, we

write

[v,a]=mycylinder(diam,ht)

Suppose we want to make a table of the volume and surface area of cylinders whose height is given and

whose diameter ranges from 1 up to some value that the user supplies. We could write the following script

file.

h=input(What is the height of the cylinders? );

max_d=input(What is the maximum diameter required? );

disp(Height

Diameter

Volume

Surface Area)

for k=1:max_d

[v,a]=mycylinder(h,k);

disp(sprintf( %7.2f

%2d

%7.2f

%7.2f,h,k,v,a))

end

Sample output is

What is the height of the cylinders? 5

What is the maximum diameter required? 6

Height

Diameter

Volume

Surface Area

5.00

1

19.63

54.98

5.00

2

39.27

70.69

5.00

3

58.90

86.39

5.00

4

78.54

102.10

5.00

5

98.17

117.81

5.00

6

117.81

133.52

Examples

1. One way to estimate the square root of 2 is to use the recurrence

xn =

1

2

),

(xn1

2

xn1

n = 1, 2, . . . ,

x0 = 3.

x=3;

for i=1:5

x=(x+2/x)/2;

disp(x)

end

This will display each value as it is calculated. If we dont need to see these intermediate values, we

can move the disp outside the loop and put it last. If we want to keep these intermediate values for

some reason then we can use a vector as below.

x=[3];

for i=1:5

x(i+1)=(x(i)+2/x(i))/2;

end

disp(x)

2. Use the iteration in Example 1, until the difference between the iterates is less than 0.005. If we

do not need all the iterates, then we can just keep the current one (called x) and the previous one

(called x_old) so we can find the difference.

x=3; x_old=x+1; % x_old is set to x+1 so that abs(x-x_old) > =0.005 on 1st time through loop

while abs(x-x_old)>=0.005

x_old=x;

x=(x+2/x)/2;

end

disp(x)

Notice the use of abs in the Boolean expression. Sometimes the iterates are decreasing and so the

difference is negative.

3

3. For the matrix A, find the component in the first column with the maximum magnitude, and which

row it is in.

A=input(Enter the matrix );

[maxabs,n]=max(abs(A(:,1)));

disp(sprintf(Max magnitude is %0.5f in row %d,maxabs,n))

Vectorisation

Vectorisation can be used in Matlab to speed up calculations involving vectors and matrices. Often this

replaces for loops.

The example on subtracting the first row of a matrix from the second row, as in the section on for loops,

can be written using vectorisation as:

A=[1 5 3 5; 6 4 -2 5;6 0 -5 2];

disp(A)

A(2,:)=A(2,:)-A(1,:);

disp(A)

Exercises

1. Write a Matlab function to perform the iterations in Example 1. The input parameters will be x0

(the initial value of x) and n ( the number of iterations to be performed).

2. Write a Matlab script file that prompts the user to enter the initial value for x and how many

iterations are required, calls the function in Exercise 1 and then displays the final result.

3. When we perform Gaussian elimination, we first subtract a multiple of the first row from the second

row. We choose this multiple so that the first element in the second row is zero after this subtraction.

Write a Matlab script file which

finds how many columns in the matrix

checks that the first element in the first row is non-zero

checks that the first element in the second row is non-zero

finds the multiple needed

uses a for loop to subtract that multiple of the first row from the second row so as to make the

first element in the second row zero.

5. You are given the following function for the secant method.

function [x,fx]=secant(xkm1,xkm2,N)

% to perform N iterations of the secant method starting with the

% values xkm1 and xkm2.

fkm1 = f(xkm1);

fkm2 = f(xkm2);

for k = 1:N

x

= xkm1 - (xkm1-xkm2)/(fkm1-fkm2)*fkm1;

xkm2 = xkm1;

xkm1 = x;

fkm2 = fkm1;

fkm1 = f(x);

end

fx=fkm1;

Write a script file, and any other files you need, to estimate a zero of f (x) = x2 ex .

- JSBSimCUJUploaded byendoparasite
- Week5 HomeworkUploaded byyashar2500
- Circuit Design With VHDL-Problem Solutions.pdfUploaded byaglyep
- Lab C++ 08 - ArraysUploaded bysafuan_alcatra
- Week5-Homework.pdfUploaded byCarlos Enciso Ojeda
- Test Bank Ninth EditionUploaded byhamed
- Chinmoy Mukherjee-Cracking the Coding Interview_ 60 Java Programming Questions and Answers (Volume 1)-CreateSpace Independent Publishing Platform (2015)Uploaded bycmeliov
- ffUploaded byFǫét Stormline
- MATLAB Statistics AssignmentUploaded byAhsan Naeem
- Intro to R Lecture 1Uploaded byDanny DeWitt
- 207 fullUploaded byVarun Bhardwaj
- Mat Lab Tutorial 5Uploaded byMd.Mazed Abdullah
- Mat Lab Plotting 2Uploaded bySathish Selvamani
- Assignment Mod 10Uploaded byAnimesh Anand
- ArraysUploaded byMark Angelo Borillo
- Memory Diagram GuideUploaded byCorina Sebesan
- practicalUploaded byAnitha Ajai
- Computer ScienceUploaded byGurjit Singh
- Voyager ScriptingUploaded bysoham
- ingles proyeccto.docxUploaded byerick garcia
- ArrayUploaded byAllehsiad Zadomen Zenitram
- Basic Mat LabUploaded byMounika
- ch1Uploaded byChristopher David Levy
- ArrayUploaded byyunindafaranika
- Interview-Questions-Answers-Data Structures and Algorithms.pdfUploaded byRaja Gopal Rao Vishnudas
- CollectionsUploaded byAshutosh Piyush
- Teaching Plan Ekt120-Sem1 2014_2015Uploaded bysyamimi
- L@$()&Uploaded bypyaemg
- nustsnanUploaded byAman Malik
- Chandan iUploaded byVenkata Bhardwaj

- Report WritingUploaded byChaubey Ajay
- Industrial ManagementUploaded byChaubey Ajay
- Engineering Graphics BasicsUploaded byJyoti Sharma
- MDUploaded byChaubey Ajay
- Thesis on RSMUploaded byChaubey Ajay
- Som Coures FileUploaded byChaubey Ajay
- Heat ExchangersUploaded byChaubey Ajay
- Boiling and CondensationUploaded byChaubey Ajay
- (702974565) btech_first_year_syllabus-2008-09Uploaded byChaubey Ajay
- Heat and Mass TfUploaded byChaubey Ajay
- NotesUploaded byChaubey Ajay
- Industrial Visit FEEDBACK FormUploaded byChaubey Ajay
- Computer Aided Design Nme 701npl 701Uploaded byChaubey Ajay
- Physiology and SportsUploaded byChaubey Ajay
- Ch3-537[1]Uploaded byEve Meg
- Beam TutorialUploaded byChaubey Ajay
- TrussUploaded byChaubey Ajay
- Centroids and Moment of Inertia CalculationUploaded bythesnake88
- pptUploaded byChaubey Ajay
- Online Topic i and II ( 2011)Uploaded byChaubey Ajay
- PresentationUploaded byEdward Cahaben
- Final Report MeUploaded byʞǝǝs Uǝ Ǝpıɥ
- Symbolic MathUploaded byChaubey Ajay
- Machine Design _1 Notes Apj Kalam Lucknow UniversityUploaded byChaubey Ajay
- Improve the Efficiency of Power Plant by SomeUploaded byChaubey Ajay

- P2 Week 10 - Diffraction & SpectraUploaded byhooloovoo
- Characterization-of-Carbohydrates.docxUploaded byNic
- Complete Idler Roller CatalogUploaded bymzarei_1982
- Feeding Behaviour of Broiler ChickensUploaded byIlham Ramadan
- Analysis of Heat Transfer in the Material during Pulsed Laser-Metal Interaction by Using Kinetic TheoryUploaded byIJAERS JOURNAL
- m120 mitsubishi s12r-pta-sUploaded byapi-252499008
- wbs-binder.pdfUploaded byKuncoro Arry Mochaa
- Softdrill NL Torque & Drag - Getting StartedUploaded byKatya Fnx
- 5070_s10_qp_12.pdfUploaded byNeural Spark Physics Cie
- pf_ind_Sj3 5-NUploaded bysanjeevverma2001
- G9SA DatasheetUploaded byjesgarmo
- P-ID0404-14-E rev 00Uploaded byMario
- Write a Shell Program to Find the Largest Among Three NumbersUploaded bySasi Natu
- AH173.pdfUploaded byGogured
- Optimal Parameters Estomation of BLDC Motor by Kohonen's Self Organizing Map Method [B. Jaganathan, Et Al]Uploaded byMario
- Earthquake Analysis of Linear SystemsUploaded byPrantik Adhar Samanta
- A STAAD Pro Course is a Must to Become a Structural EngineerUploaded bysandesh bukate
- Chapter 4b_electronic Atomic StructureUploaded bykakakcun
- 375hw5Uploaded byriddler_007
- various stages in stress strain curveUploaded byganesh_the_aviator
- lab 2Uploaded byapi-383698554
- 8th Syllabus [PDF Library]Uploaded bykp1292
- Manj-10-IECR (1)Uploaded byAnonymous 1hOgJqwZuz
- g - Articulo - Jibson - Predicting Earthquake-Induced Landslide Displacements Using Newmark's Sliding Block AnalysisUploaded byFabián Arquín Bolaños
- Anchor Escapement - WikipediaUploaded byAri Sudrajat
- Sm1238 Energy Meter 480vac Manual en-En en-USUploaded byFelipe Zambrano
- Dic of engg.Uploaded byUssama Saleem
- Management Science Lecture NotesUploaded byAbhijit Pathak
- solution to-9.18.pdfUploaded byPraveen AK
- 26771259 Matriculation Physics Quantization of LightUploaded byMuhammadArifAnuar