MEEN 2240
PROGRAMMING FOR
MECHANICAL ENGINEERS
Instructor: Dr. Yunwei Xu
Dept of Mechanical Engineering
University of North Texas
Chapter 3
Algorithms & Scripts
Input and Output
Copyright © 2020 Yunwei Xu, PhD 2
Algorithms & Scripts
• An algorithm is the sequence of steps to be designed to solve a problem
• Top-down design: Separate a solution into steps, then solve each one
• Command window is a good tool for calculations, but not the best approach to solve longer
problems.
• Script file is more proper for longer problems and modular codes
• Click on “New” then “Script” to create a script
• Save a script file with the format (extension .m)
To create a new script To save a script To set a location to save the script
Copyright © 2020 Yunwei Xu, PhD 3
Run Script Files
Two ways to run the script Click on “Run Section”
• Click on “Run” button • When there are more than
• Type the script name at one codes in a file, to use
the Command window %% to run the codes
separately, then click on
“Run Section”
Copyright © 2020 Yunwei Xu, PhD 4
Documentation
• Scripts should be documented using comments
• Comments are used to describe how the script works
• Comments will be read by the other users when sharing the file
• Add a comment by using a % at the end of that line
• Comments will show green color after %
• Comments are ignored by MATLAB
Copyright © 2020 Yunwei Xu, PhD 5
Input (data)
• When a user wants to use your code to run a result by inputting data
• The data could be a number, cost, height, etc.
• The response to the input prompt can be any MATLAB expression, which is selected
using the variables in the current workspace.
• Two options for inputs
• Numbers
• user_entry = input('prompt')
• Strings (text): ‘s’ means a string will be input
• user_entry =input('prompt',’s’)
Copyright © 2020 Yunwei Xu, PhD 6
Output (data)
• There are two basic output functions:
• disp—a quick way to display output
• fprintf—allows formatted output
Example: disp
• Printing vectors and matrices are easier by disp
• disp—output data without formatting
Click “Run”
Copyright © 2020 Yunwei Xu, PhD 7
Output - fprintf
The fprintf function allows you to “display" information to the screen for the user to
view. The 'f' in printf stands for formatted. That means you can "format" how the data is
displayed to make it easy to read.
• For instance: The fprintf function prints an array of characters to the screen
• fprintf(‘Good Morning\n’)
Click “Run”
• When using the % signs to print the data, we must use the same number of % signs as the
number of variables. Some common format options:
• %d - print a whole number
• %f - print a float Note: '%’ sign here is not a comment, but
• %s - print a string "formatting"
• %c - print a single character
• \n - print a new line
Copyright © 2020 Yunwei Xu, PhD 8
Output - fprintf
• Use %#x where # is an integer and x is the conversion character to specify the field
width of #.
• field width - x is an integer that indicates how many available in the output
• To allow 8 spaces for the output, field width = 8
• field width - # is a conversion character to specify the desired format, Examples:
• %8d – 8 spaces for an integer value
• %8s – 8 spaces for a string
Note: If the specified field width is smaller than the value, the value is still displayed
• Specify # of digits past decimal point with floating point numbers
• Examples:
• %8.5f—field width of 8 spaces with 5 digits past the decimal
• %.3f—field width is automatically chosen and there will be 3 digits past the decimal (this
example means field width doesn’t have to be specified)
Copyright © 2020 Yunwei Xu, PhD 9
Output Format
Some common format options:
• %d : print a whole number
• %f : print a float
• %s : print a string
• %c : print a single character
• \n : print a new line
• \t : print a tab
• \\ : print a slash
• %% : print a percent sign
• - : left justify (e.g. %-5d)
• ‘ ‘ : print one single quote
Copyright © 2020 Yunwei Xu, PhD 10
Examples of fprintf
Print a new line
Example 1:
MountHeight=8.848;
fprintf('Mount Everest Height is %.2f km\n',MountHeight);
2 digits past the decimal
Example 2:
Salary=200.458;
days=3;
fprintf('His salary for %6d days = %.2f\n',days,Salary);
6 spaces for an integer value
Copyright © 2020 Yunwei Xu, PhD 11
Examples of fprintf
Example 3:
author ='Yuval'
book ='A Brief History of Humankind';
fprintf('%-20s!\n',author,book)
15 blank spaces, since
“Yuval” was 5 0 blank spaces, even
characters and field though there was a 28
Left aligned characters string, we
width is specified as 20
specified field width of
20, it will still display
the full string
Copyright © 2020 Yunwei Xu, PhD 12
Scripts
• Combining input and output in scripts is normal
• General outline of a script:
• input - get data
• Perform calculations
• fprintf - display formatted data
• To use semicolons (;) to control the output
• fprintf should be where output is displayed
Copyright © 2020 Yunwei Xu, PhD 13
Example of Scripts
Example 4:
• Body mass index (BMI) is a person’s weight in kilograms divided by the square of
height in meters. BMI is an inexpensive and easy screening method for weight
category
• BMI = weight (kg)/[height (m)]2
• We want a script that will prompt for the weight and height, then calculate and
print the BMI. We want to design a script like this:
>> BMIscript
Please enter your weight in kg: 80
Please enter your height in m: 1.85
Your BMI is 23.37
>>
Copyright © 2020 Yunwei Xu, PhD 14
Example of Scripts
weight=input('Please enter your weight in kilograms
(kg):');
height=input('Please enter your height in meters (m):');
BMI=weight/height^2;
fprintf('Your BMI is = %.2f',BMI);
Copyright © 2020 Yunwei Xu, PhD 15
Practices
Example 5: Enter the following commands to see different forms of output.
fprintf('%.3f\n',sqrt(314))
fprintf('%10.5f\n',sqrt(314))
fprintf('%d\n',round(sqrt(314)))
fprintf('The array is %dx%d. \n',4,5)
fprintf('%s\n','It is a cat!')
fprintf('%s\t','abcdefg') Recall some common format options:
fprintf('%-10.2f\n',pi)
fprintf('%s\t','abcdefg') • %d : print a whole number
fprintf('%10.2f',pi) • %f : print a float
• %s : print a string
• %c : print a single character
• \n : print a new line
• \t : print a tab
• \\ : print a slash
• %% : print a percent sign
• - : left justify (e.g. %-5d)
• ‘ ‘ : print one single quote
Copyright © 2020 Yunwei Xu, PhD 16
Practices
Example 6: Calculate the total cost of your monthly electricity charge.
A power company charges 6.6 cents per kilowatt hour (KHW) for providing electricity. Write
a script “power_charge” that prompt the user for the number of KWH used in each month
and will print the charge for the month in dollars.
% Calculates and prints charge to customer for electricity
kwh = input('How many KWH this month: ‘);
charge = kwh * 6.6 / 100;
fprintf('Your charge for %d KWH will be $%.2f.\n',kwh,charge)
Copyright © 2020 Yunwei Xu, PhD 17
Practices
Example 7:
For a bubble, the surface tension force in the downward direction is
Fd = 4 Tr
where T is the surface tension measured in force per unit length and r is the radius of the
bubble. For water, the surface tension at 25⁰C is 72 dyn/cm. Write a script named ‘surftens’
that will prompt the user for the radius of a water bubble in centimeters, calculate Fd in 25⁰C.
% Calculates downward surface tension force of a bubble
radius = input('Enter the radius of the bubble in cm: ');
water_tens = 72;
f_down = 4 * pi * water_tens * radius;
fprintf('For a bubble with a radius of %.1f, the surface\n', ...
radius)
fprintf('tension force in the downward direction is %.2f\n',...
f_down)
Copyright © 2020 Yunwei Xu, PhD 18