0% found this document useful (0 votes)
7 views6 pages

1.2 Chapter 3 Examples

The document outlines a series of MATLAB scripts and commands for calculating areas of geometric shapes, temperature conversions, plotting functions, and data handling. It includes instructions for creating scripts to compute the area of circles and rectangles, display formatted output, and plot sine and cosine waves. Additionally, it covers loading data from files, performing calculations on car motion, and creating a grade calculator function.

Uploaded by

hectvelez042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

1.2 Chapter 3 Examples

The document outlines a series of MATLAB scripts and commands for calculating areas of geometric shapes, temperature conversions, plotting functions, and data handling. It includes instructions for creating scripts to compute the area of circles and rectangles, display formatted output, and plot sine and cosine waves. Additionally, it covers loading data from files, performing calculations on car motion, and creating a grade calculator function.

Uploaded by

hectvelez042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

STEM Course Prep

In-Class Activities
Chapter 3

Slides 1-6

1. Create a script to calculate the area of a circle with a radius of 10”. Call the script area.m.

Enter the following code in the script:


%This script calculates the area of a circle given a radius.
Radius = 10;
Area=2*pi*Radius;

2. To see the lines of code in area.m use the type command.

In the command window, enter the following:


type area

3. Let’s say you forgot what the area.m script does. Use the help command to find out.

In the command window, enter the following:


help area

Notice the first comment line is repeated. It is always a good idea to put a detailed description in for the first
comment.

Slide 7-8

4. Now create a script that calculates the area of a rectangle. Ask the user to input the base and height of the
rectangle. Also allow the user to supply a name of the rectangle. Call the script rectangle1.m.

% This script calculates the area of a rectangle given user-defined base and
% height values.
Base=input(‘Enter the base of the rectangle in inches ’)
Height=input(‘Enter the height of the rectangle in inches ’)
Name=input(‘Enter the name of the rectangle ’,’s’)
Area=base*height

5. Create a script to calculate temperature in Fahrenheit if given temperature in Celsius. Display the result using
the disp command. Call the script temp_F.m.

Enter the following in the script file:


temp_C = input(‘Enter the temperature in Celsius ‘);
temp_f=(9/5)*temp_C+32;
disp(temp_f)
Slides 9-14

6. Enter the following commands:


fprintf('%.0f',pi)
pause
fprintf('%.7f',pi)

Result: 33.1415927 Need to use the newline character to make the output more readable.

7. Enter the following commands:


fprintf('%.0f\n',pi)
pause
fprintf('%.7f\n',pi)

Result:
3
3.1415927

8. Enter the following commands to see different forms of output.


fprintf('%.5f\n',sqrt(786))
fprintf('%20.10f\n',sqrt(786))
fprintf('%d\n',round(sqrt(786)))
fprintf('The array is %dx%d. \n',2,3)
fprintf('%s\n','It is Tuesday!')
fprintf('%s\t','Hello')
fprintf('%-10.2f',pi)

Result:
28.03569
28.0356915378
28
The array is 2x3.
It is Tuesday!
Hello 3.14 >>

Slides 15-17

9. Create a script to determine the amount of money spent on office supplies. Suppress all output except the
statement giving the total cost of the supplies. Call the script ‘supplies’.
%This script will calculate the total cost of buying pens, paper and tape.
pens=input('Enter the number of pens purchased ');
paper=input('Enter the number of packages of paper purchased ');
tape=input('Enter the number of rolls of tape purchased ');
pretax_cost=pens*0.25+paper*5.99+tape*2.76;
total_cost=pretax_cost*1.0825;
fprintf('The total cost of %d pens, %d reams of paper and %d rolls of tape
is $%.2f.\n',...
pens, paper, tape,total_cost)

Result:
Enter the number of pens purchased 12
Enter the number of packages of paper purchased 15
Enter the number of rolls of tape purchased 6
The total cost of 12 pens, 15 reams of paper and 6 rolls of tape is $118.44.

Slides 18-21

10. Plot a sine wave for values between 0 and 4𝜋𝜋, in increments of 𝜋𝜋/40. Use a cyan dashdot line with square data
markers.
x=0:pi/40:4*pi;
plot(x,sin(x),’c-.s’)

11. Re plot the sine wave but this time use a magenta dotted line with left triangle markers.
plot(x,sin(x),’m:<’)

Slide 22-24

12. Using the sine wave plot from above, add labels and a title.
xlabel('Angle (rad)')
ylabel('sin(x)')
title('Sine function for values between 0 to 4*pi')

13. Now change the lengths of the axes.

axis([-1 16 -2 2])

Now the x-axis goes from -1 to 16 and the y-axis goes from -2 to 2.

Slide 25-27
14. Add a grid to the previous plot and add a cosine wave using the same values of x.
hold on
plot(x,cos(x),'g--*')
ylabel('trig function')
legend ('sin(x)','cos(x)')
grid
hold off

15. Add a label in the plot that denotes where the max value can be found and at point (2,-1.5) put text.
gtext('max height')
text(2,-1.5,'I am coordinate (2,-1.5)')

16. Plot a circle using the sine and cosine functions.

x=0:pi/40:2*pi;
plot(sin(x),cos(x))

The circle doesn’t appear exactly round. Use the following command to correct that.

axis equal

Slides 28-29

17. Download the ‘li_lab_data.txt’ file. Make sure you save the file in your working directory. Load the file into
MATLAB. The file contains volumetric flow rate and pressure change data. Store each column of data in its own
vector. Plot the data points using red * markers. Label the axes. Use a grid.
load li_lab_data.txt
volume_flow=li_lab_data(:,1);
pressure_change=li_lab_data(:,2);
plot(volume_flow,pressure_change,'r* ')
xlabel('volumetric flow (m^3/sec)')
ylabel('pressure change (Pa)')
grid on

18. A car moves in a straight line such that for a short time its position, velocity and acceleration are defined as
shown below. Determine the values for position, velocity and acceleration for times starting at 0 and ending at
10 sec. Use 0.5 sec increments. Put the time, position, velocity and acceleration data into a table called
car_data. Save this table to a file called ‘car.txt’. Verify the data is in the file.
t=0:0.5:10;
position=t.^3+t.^2;
velocity=3*t.^2+2*t;
acceleration=6*t+2;
car_data(:,1)=t';
car_data(:,2)=position';
car_data(:,3)=velocity';
car_data(:,4)=acceleration';
save car.txt car_data -ascii
19. Let’s add data to the car.txt file. Now calculate position, velocity and acceleration for time values of 10.2 to 15
sec. Use 0.2 sec increments. Append this new data to the data in car.txt.
clear all
t=10.2:0.2:15;
position=t.^3+t.^2;
velocity=3*t.^2+2*t;
acceleration=6*t+2;
car_data(:,1)=t';
car_data(:,2)=position';
car_data(:,3)=velocity';
car_data(:,4)=acceleration';
save car.txt car_data -ascii -append

Slides 30-39

20. Create a function called ‘grade_calculator’ to calculate the grades for a class of 10 students. Inputs: homework
average, exam 1, exam 2, final exam. Outputs: final average.

Create the function first. Go to the ‘new’ tab and select function. Fill in the details.
function [ final_grade ] = grade_calculator(… homework,test1,test2,final )
%This function calculates the final average for MEEN 2222.
%Inputs:homework average
% test 1 grade
% test 2 grade
% final exam grade
%Output: final average for the course

final_grade=homework*.10+test1*.25+test2*.25+final*.40;

end

Now download ‘grades.txt’ and load it in MATLAB. This data file contains four columns: homework, test 1, test 2,
final exam. Input this data into the grade_calculator function. The function will calculate the final averages.
Save this data in a file called ‘final_averages.txt’.
load grades.txt
averages=grade_calculator(grades(:,1),grades(:,2),grades(:,3),…
grades(:,4));
save final_averages.txt averages -ascii

21. The difference between the total and static pressures can be used to find the velocity of water using the
following equation:

𝑣𝑣 = 1.016�𝑃𝑃𝑡𝑡 − 𝑃𝑃𝑠𝑠

Create a script that will:

• Ask the user to enter values for total and static pressure. Let total pressure =1000, static pressure= 500.
• Write a function named fluid_velocity that will calculate the fluid velocity
o Input arguments: total and static pressures
o Output argument: velocity
o Use formatted print statement to display result (round value down to nearest whole number)

Script file:
Pt=input(‘Enter the total pressure: ‘);
Ps=input(‘Enter the static pressure: ‘);
velocity=fluid_velocity(Pt,Ps);
fprintf(‘\nThe fluid velocity is %d.\n’,floor (velocity))

fluid_velocity.m
function [v]=fluid_velocity(Pt,Ps)
%This function calculates the velocity of a moving fluid
% given the total and static pressures
v=1.016*sqrt(Pt-Ps);
end

You might also like