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

it is the relatively stable flow of income
Chidubem Reply
what is circular flow of income
Divine Reply
branches of macroeconomics
SHEDRACK Reply
what is Flexible exchang rate?
poudel Reply
is gdp a reliable measurement of wealth
Atega Reply
introduction to econometrics
Husseini Reply
Hi
mostafa
hi
LEMLEM
hello
Sammol
hi
Mahesh
bi
Ruqayat
hi
Ruqayat
Hi fellas
Nyawa
hey
Sammol
hi
God
hello
Jahara
Good morning
Jorge
hi
abubakar
hi
Nmesoma
hi
Mahesh
Hi
Tom
Why is unemployment rate never zero at full employment?
Priyanka Reply
bcoz of existence of frictional unemployment in our economy.
Umashankar
what is flexible exchang rate?
poudel
due to existence of the pple with disabilities
Abdulraufu
the demand of a good rises, causing the demand for another good to fall
Rushawn Reply
is it possible to leave every good at the same level
Joseph
I don't think so. because check it, if the demand for chicken increases, people will no longer consume fish like they used to causing a fall in the demand for fish
Anuolu
is not really possible to let the value of a goods to be same at the same time.....
Salome
Suppose the inflation rate is 6%, does it mean that all the goods you purchase will cost 6% more than previous year? Provide with reasoning.
Geetha Reply
Not necessarily. To measure the inflation rate economists normally use an averaged price index of a basket of certain goods. So if you purchase goods included in the basket, you will notice that you pay 6% more, otherwise not necessarily.
Waeth
discus major problems of macroeconomics
Alii Reply
what is the problem of macroeconomics
Yoal
Economic growth Stable prices and low unemployment
Ephraim
explain inflationcause and itis degre
Miresa Reply
what is inflation
Getu
increase in general price levels
WEETO
Good day How do I calculate this question: C= 100+5yd G= 2000 T= 2000 I(planned)=200. Suppose the actual output is 3000. What is the level of planned expenditures at this level of output?
Chisomo Reply
how to calculate actual output?
Chisomo
how to calculate the equilibrium income
Beshir
Criteria for determining money supply
Thapase Reply
who we can define macroeconomics in one line
Muhammad
Aggregate demand
Mohammed
C=k100 +9y and i=k50.calculate the equilibrium level of output
Mercy Reply
Hi
Isiaka
Hi
Geli
hy
Man
👋
Bahunda
hy how are you?
Man
ys
Amisha
how are you guys
Sekou
f9 guys
Amisha
how are you guys
Sekou
ys am also fine
Amisha
fine and you guys
Geli
from Nepal
Amisha
nawalparasi district from belatari
Amisha
nd u
Amisha
I am Camara from Guinea west Africa... happy to meet you guys here
Sekou
ma management ho
Amisha
ahile becheclor ho
Amisha
hjr ktm bta ho ani k kaam grnu hunxa tw
Amisha
belatari
Amisha
1st year ho
Amisha
nd u
Amisha
ahh
Amisha
kaha biratnagar
Amisha
ys
Amisha
kina k vo
Amisha
money as unit of account means what?
Kalombe
A unit of account is something that can be used to value goods and services and make calculations
Jim
all of you please speak in English I can't understand you're language
Muhammad
I want to know how can we define macroeconomics in one line
Muhammad
it must be .9 or 0.9 no Mpc is greater than 1 Y=100+.9Y+50 Y-.9Y=150 0.1Y/0.1=150/0.1 Y=1500
Kalombe
Mercy is it clear?😋
Kalombe
hi can someone help me on this question If a negative shocks shifts the IS curve to the left, what type of policy do you suggest so as to stabilize the level of output? discuss your answer using appropriate graph.
Galge Reply
if interest rate is increased this will will reduce the level of income shifting the curve to the left ◀️
Kalombe
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