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

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