<< Chapter < Page Chapter >> Page >

Upon running the file, the output.txt file will display the following:

The radius of acetylene bottle: 0.3 meters The height of cylindrical part of acetylene bottle: 1.5 metersThe volume of the acetylene bottle: 0.480664 cubic meters.

Loops

In programming, a loop executes a set of code a specified number of times or until a condition is met.

For loop

This loop iterates an index variable from an initial value using a specified increment to a final value and runs a set of code. The for loop syntax is the following: for loop_index=vector_statement code... codeend

Calculate y x for x using an increment of 4 . for x=-pi:pi/4:pi y=cos(x);fprintf('%8.3f %8.2f \n',x,y); end

In the brief script above, x is the loop index that is initiated from and incremented with 4 to a final value of . At the end of each increment, y x is calculated and displayed with the fprintf command. This process continues until x .

From a previous exercise we know \n creates a new line when included in the fprintf command. Here, we also use %8.3f to specify eight spaces and three decimal places for the first variable x. Likewise %8.2f specifies the formatting for the second variable y but in this case, y is displayed with two decimal places. The result is the following: -3.142 -1.00 -2.356 -0.71-1.571 0.00 -0.785 0.710.000 1.00 0.785 0.711.571 0.00 2.356 -0.713.142 -1.00

We can improve our code by adding formatting lines as follows: clear; clc; fprintf(' x cos(x)\n') % title rowfprintf(' ----------------\n') % title row for x=-pi:pi/4:pi % loop_index=inital_value:increment_value:final_valuey=cos(x); % code to calculate cos(x) fprintf('%8.3f %8.2f \n',x,y); % code to print the output to screenend

Screen output: x cos(x) -----------------3.142 -1.00 -2.356 -0.71-1.571 0.00 -0.785 0.710.000 1.00 0.785 0.711.571 0.00 2.356 -0.713.142 -1.00

While loop

Like the for loop, a while loop executes blocks of code over and over again however it runs as long as the test condition remains true. The syntax of a while loop is while test_condition code... codeend

Using a while loop, calculate y x for x using an increment of 4 .

This time we need to initialize the x value outside the loop and then state the test condition in the first line of the while loop. We also need to create an increment statement within the while loop: x=-pi; while x<=pi y=cos(x);fprintf('%8.3f %8.2f \n',x,y); x = x + (pi/4);end

The result is the same as that of the previous example: -3.142 -1.00 -2.356 -0.71-1.571 0.00 -0.785 0.710.000 1.00 0.785 0.711.571 0.00 2.356 -0.713.142 -1.00

Now we can improve the code by adding extra formatting lines and comments: clear; clc; fprintf(' x cos(x)\n') % title rowfprintf(' ----------------\n') % title row x=-pi; % initiating the x valuewhile x<=pi % stating the test condition y=cos(x); % calculating the value of yfprintf('%8.3f %8.2f \n',x,y); % printing a and y x = x + (pi/4); % iterating to the next stepend

The result should look the same as before. x cos(x) -----------------3.142 -1.00 -2.356 -0.71-1.571 0.00 -0.785 0.710.000 1.00 0.785 0.711.571 0.00 2.356 -0.713.142 -1.00

The diary Function

Instead of writing a script from scratch, we sometimes solve problems in the Command Window as if we are using a scientific calculator. The steps we perform in this fashion can be used to create an m-file. For example, the diary function allows us to record a MATLAB session in a file and retrieve it for review. Reviewing the file and by copying relevant parts of it and pasting them in to an m-file, a script can be written easily.

Typing diary at the MATLAB prompt toggles the diary mode on and off. As soon as the diary mode is turned on, a file called diary is created in the current directory. If you like to save that file with a specific name, say for example problem16, type
>>diary problem16.txt .
A file named problem16.txt will be created. The following is the content of a diary file called problem16.txt. Notice that in that session, the user is executing the four files we created earlier. The user's keyboard input and the resulting display output is recorded in the file. The session is ended by typing diary which is printed in the last line. This might be useful to create a record of your work to hand in with a lab or to create the beginnings of an m-file.

AcetyleneBottle Vol_total =0.4807 AcetyleneBottleInteractiveEnter the radius of acetylene bottle in meters .3 Enter the height of cylinderical part of acetylene bottle in meters 1.5Vol_total = 0.4807AcetyleneBottleInteractiveDisp This script computes the volume of an acetylene bottleEnter the radius of acetylene bottle in meters .5 Enter the height of cylinderical part of acetylene bottle in meters 1.6The volume of the acetylene bottle is1.5184 AcetyleneBottleInteractiveDisp1This script computes the volume of an acetylene bottle:Enter the radius of acetylene bottle in meters .9 Enter the height of cylinderical part of acetylene bottle in meters 1.9The volume of the acetylene bottle is 6.3617 cubic meters.diary

Style guidelines

Try to apply the following guidelines when writing your scripts:

  • Share your code or programs with others, consider adopting one of Creative Commons or GNU General Public License schemes
  • Include your name and contact info in the opening lines
  • Use comments liberally
  • Group your code and use proper indentation
  • Use white space liberally
  • Use descriptive names for your variables
  • Use descriptive names for your m-files

Summary of key points

  1. A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m.
  2. Functions such as input , disp and num2str can be used to make scripts interactive,
  3. fopen , fprintf and fclose functions are used to create output files,
  4. A for loop is used to repeat a specific block of code a definite number of times.
  5. A while loop is used to repeat a specific block of code an indefinite number of times, until a condition is met.
  6. The diary function is useful to record a MATLAB command window session from which an m-file can be easily created,
  7. Various style guidelines covered here help improve our code.

Questions & Answers

what is variations in raman spectra for nanomaterials
Jyoti Reply
I only see partial conversation and what's the question here!
Crow Reply
what about nanotechnology for water purification
RAW Reply
please someone correct me if I'm wrong but I think one can use nanoparticles, specially silver nanoparticles for water treatment.
Damian
yes that's correct
Professor
I think
Professor
what is the stm
Brian Reply
is there industrial application of fullrenes. What is the method to prepare fullrene on large scale.?
Rafiq
industrial application...? mmm I think on the medical side as drug carrier, but you should go deeper on your research, I may be wrong
Damian
How we are making nano material?
LITNING Reply
what is a peer
LITNING Reply
What is meant by 'nano scale'?
LITNING Reply
What is STMs full form?
LITNING
scanning tunneling microscope
Sahil
how nano science is used for hydrophobicity
Santosh
Do u think that Graphene and Fullrene fiber can be used to make Air Plane body structure the lightest and strongest. Rafiq
Rafiq
what is differents between GO and RGO?
Mahi
what is simplest way to understand the applications of nano robots used to detect the cancer affected cell of human body.? How this robot is carried to required site of body cell.? what will be the carrier material and how can be detected that correct delivery of drug is done Rafiq
Rafiq
what is Nano technology ?
Bob Reply
write examples of Nano molecule?
Bob
The nanotechnology is as new science, to scale nanometric
brayan
nanotechnology is the study, desing, synthesis, manipulation and application of materials and functional systems through control of matter at nanoscale
Damian
Is there any normative that regulates the use of silver nanoparticles?
Damian Reply
what king of growth are you checking .?
Renato
What fields keep nano created devices from performing or assimulating ? Magnetic fields ? Are do they assimilate ?
Stoney Reply
why we need to study biomolecules, molecular biology in nanotechnology?
Adin Reply
?
Kyle
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
Adin
why?
Adin
what school?
Kyle
biomolecules are e building blocks of every organics and inorganic materials.
Joe
anyone know any internet site where one can find nanotechnology papers?
Damian Reply
research.net
kanaga
sciencedirect big data base
Ernesto
Introduction about quantum dots in nanotechnology
Praveena Reply
what does nano mean?
Anassong Reply
nano basically means 10^(-9). nanometer is a unit to measure length.
Bharti
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
Damian Reply
absolutely yes
Daniel
how did you get the value of 2000N.What calculations are needed to arrive at it
Smarajit Reply
Privacy Information Security Software Version 1.1a
Good
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get the best Algebra and trigonometry course in your pocket!





Source:  OpenStax, A brief introduction to engineering computation with matlab. OpenStax CNX. Nov 17, 2015 Download for free at http://legacy.cnx.org/content/col11371/1.11
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'A brief introduction to engineering computation with matlab' conversation and receive update notifications?

Ask