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

A golfer on a fairway is 70 m away from the green, which sits below the level of the fairway by 20 m. If the golfer hits the ball at an angle of 40° with an initial speed of 20 m/s, how close to the green does she come?
Aislinn Reply
cm
tijani
what is titration
John Reply
what is physics
Siyaka Reply
A mouse of mass 200 g falls 100 m down a vertical mine shaft and lands at the bottom with a speed of 8.0 m/s. During its fall, how much work is done on the mouse by air resistance
Jude Reply
Can you compute that for me. Ty
Jude
what is the dimension formula of energy?
David Reply
what is viscosity?
David
what is inorganic
emma Reply
what is chemistry
Youesf Reply
what is inorganic
emma
Chemistry is a branch of science that deals with the study of matter,it composition,it structure and the changes it undergoes
Adjei
please, I'm a physics student and I need help in physics
Adjanou
chemistry could also be understood like the sexual attraction/repulsion of the male and female elements. the reaction varies depending on the energy differences of each given gender. + masculine -female.
Pedro
A ball is thrown straight up.it passes a 2.0m high window 7.50 m off the ground on it path up and takes 1.30 s to go past the window.what was the ball initial velocity
Krampah Reply
2. A sled plus passenger with total mass 50 kg is pulled 20 m across the snow (0.20) at constant velocity by a force directed 25° above the horizontal. Calculate (a) the work of the applied force, (b) the work of friction, and (c) the total work.
Sahid Reply
you have been hired as an espert witness in a court case involving an automobile accident. the accident involved car A of mass 1500kg which crashed into stationary car B of mass 1100kg. the driver of car A applied his brakes 15 m before he skidded and crashed into car B. after the collision, car A s
Samuel Reply
can someone explain to me, an ignorant high school student, why the trend of the graph doesn't follow the fact that the higher frequency a sound wave is, the more power it is, hence, making me think the phons output would follow this general trend?
Joseph Reply
Nevermind i just realied that the graph is the phons output for a person with normal hearing and not just the phons output of the sound waves power, I should read the entire thing next time
Joseph
Follow up question, does anyone know where I can find a graph that accuretly depicts the actual relative "power" output of sound over its frequency instead of just humans hearing
Joseph
"Generation of electrical energy from sound energy | IEEE Conference Publication | IEEE Xplore" ***ieeexplore.ieee.org/document/7150687?reload=true
Ryan
what's motion
Maurice Reply
what are the types of wave
Maurice
answer
Magreth
progressive wave
Magreth
hello friend how are you
Muhammad Reply
fine, how about you?
Mohammed
hi
Mujahid
A string is 3.00 m long with a mass of 5.00 g. The string is held taut with a tension of 500.00 N applied to the string. A pulse is sent down the string. How long does it take the pulse to travel the 3.00 m of the string?
yasuo Reply
Who can show me the full solution in this problem?
Reofrir Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




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