<< 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

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 to know photocatalytic properties of tio2 nanoparticles...what to do now
Akash Reply
it is a goid question and i want to know the answer as well
Maciej
characteristics of micro business
Abigail
for teaching engĺish at school how nano technology help us
Anassong
Do somebody tell me a best nano engineering book for beginners?
s. Reply
there is no specific books for beginners but there is book called principle of nanotechnology
NANO
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
s.
fullerene is a bucky ball aka Carbon 60 molecule. It was name by the architect Fuller. He design the geodesic dome. it resembles a soccer ball.
Tarell
what is the actual application of fullerenes nowadays?
Damian
That is a great question Damian. best way to answer that question is to Google it. there are hundreds of applications for buck minister fullerenes, from medical to aerospace. you can also find plenty of research papers that will give you great detail on the potential applications of fullerenes.
Tarell
what is the Synthesis, properties,and applications of carbon nano chemistry
Abhijith Reply
Mostly, they use nano carbon for electronics and for materials to be strengthened.
Virgil
is Bucky paper clear?
CYNTHIA
carbon nanotubes has various application in fuel cells membrane, current research on cancer drug,and in electronics MEMS and NEMS etc
NANO
so some one know about replacing silicon atom with phosphorous in semiconductors device?
s. Reply
Yeah, it is a pain to say the least. You basically have to heat the substarte up to around 1000 degrees celcius then pass phosphene gas over top of it, which is explosive and toxic by the way, under very low pressure.
Harper
Do you know which machine is used to that process?
s.
how to fabricate graphene ink ?
SUYASH Reply
for screen printed electrodes ?
SUYASH
What is lattice structure?
s. Reply
of graphene you mean?
Ebrahim
or in general
Ebrahim
in general
s.
Graphene has a hexagonal structure
tahir
On having this app for quite a bit time, Haven't realised there's a chat room in it.
Cied
what is biological synthesis of nanoparticles
Sanket Reply
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