0% found this document useful (0 votes)
6 views7 pages

MATLAB Energy Unit Conversion Script

The document provides solutions for a MATLAB course, focusing on programming principles such as unit conversion, series summation, and graphical representation of data. It includes scripts for converting energy units, calculating sums of series using loops, and creating terrain profiles with soil thickness. The solutions utilize MATLAB commands and structures like switch-case and for-end loops to perform calculations and display results.

Translated by

ScribdTranslations
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)
6 views7 pages

MATLAB Energy Unit Conversion Script

The document provides solutions for a MATLAB course, focusing on programming principles such as unit conversion, series summation, and graphical representation of data. It includes scripts for converting energy units, calculating sums of series using loops, and creating terrain profiles with soil thickness. The solutions utilize MATLAB commands and structures like switch-case and for-end loops to perform calculations and display results.

Translated by

ScribdTranslations
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

MATLAB Course UNIL-FGSE - Winter 2009-2010

III. Programming Principles - Solution


Auteur : Alexandre Loye

III. Programming Principles - Correction

1. Switch – Case structure: Unit conversion of energy


Write a small script that allows converting an amount of energy among several units.
energy: joule, calorie, Ft-lb and eV. Organize the program so that it asks for input of the
amount of energy, its unit, as well as the new unit. The output will be the amount of energy
in the new unit (draw inspiration from the examples in chapter 3).

The conversion factors between units are: 1J = 0.738 ft-lb = 0.239 cal = 6.24*1018eV.

En utilisant votre programme, déterminer a) 325J en ft-lb, b) 432 cal en Joules, c) 6.8 eV en
calories.

Use the command 'disp' to display the result on the screen (use the help!)

Complete the program using the if - else - end structure to generate a


error message if the units are entered incorrectly.

Enter the value of energy, its unit, and the new unit
% désirée:
V_in = input('quantité d''énergie à convertir: ');
Ein_unit = input('entrer son unité(J, ft-lb, cal ou eV): ','s');
Eout_unit = input('enter the desired unit (J, ft-lb, cal or ...
eV): ','s');

% assigns the value 0 to potential errors


error = 0; %l’erreur est fausse

use the switch expression to choose between the units


%initials. For the 4 initial units, convert firstly
%le %V_in in Joules
switch Ein_unit
case 'J'
E_Joule = V_in;

case 'ft-lb'
E_Joule = V_in/0.738;

case 'cal'
E_Joule = V_in/0.239;

case 'eV'
E_Joule = V_in/(6.24*10^18);

otherwise
error = 1; %l’erreur est vraie
end

1/7
MATLAB Course UNIL-FGSE - Winter 2009-2010
III. Programming Principles - Solution
Auteur : Alexandre Loye

% use the switch expression to choose between units


% finals. For each final unit, convert the obtained result.
% previously (in Joules) in the desired final unit.

switch Eout_unit
case 'J'
E_new = E_Joule;

case 'ft-lb'
E_new = E_Joule*0.738;

case 'cal'
E_new = E_Joule*0.239;

case 'eV'
E_new = E_Joule * 6.24e18;

otherwise
error = 1;
end

% Message d'erreur si les unités sont entrées incorrectement


if error
The units are entered incorrectly!
else
fprintf('%g %s = %g %s\n', V_in, Ein_unit, E_new, Eout_unit)
end

Réponse :

325 J = 239.85 ft-lb

432 cal = 1807.53 J

6.8 eV = 2.60449e-019 cal

2. Loop structure: the sum of a series


• Use the for - end structure to calculate the sum of the n terms of the series:
n k
∑ (−1)2 kk
.
k =1

Exécuter le programme pour n = 4 , n = 20, n = 102Deduce for n = +infinity.

input the number of terms n


n = input('number of terms n? ')

First, set the sum = 0


S = 0;

% use the for-end loop to generate the sum

2/7
MATLAB Course UNIL-FGSE - Winter 2009-2010
III. Programming Principles - Solution
Auteur : Alexandre Loye

for k=1:n
S = S + (-1)^k*k/2^k;
end

the sum of the %g terms of the series is: %f

Réponses :

the sum of the 4 terms of the series is: -0.125000

the sum of the 20 terms of the series is: -0.222216

the sum of the 100 terms of the series is: -0.222222

the sum of the 1e+006 terms of the series is: -0.222222

∞ k 2k
• The function cos(x) can be written as a Taylor series: cos (x) = ∑ (−1)(2k)!x .
k =0

The input arguments are the angle x in degrees (note: Matlab is in radians) therefore
let the number n of terms in the series. Use the for - end structure to calculate
cos(210°) with n = 3 and n = 8. Compare your answer with the function cos(x)
implemented in Matlab.

%input arguments: l’angle x (en degrés) et n the nombre de termes

x = input('the angle (in degrees) ')


n = input('number of terms in the Taylor series ')

transform the angle x into radians


xr = x*pi/180;

%set the sum = zero


S = 0;

use the for-end loop to generate the sum

for k=0:n
S = S + (-1)^k*xr^(2*k) / factorial(2*k);
end

display the answer for cos(x,n)


printf('the function cos(%g,%g)= %f ', x, n, S)

%comparison with the function cos(x)


cosX = cos(xr);

fprintf('the Matlab function cos of %g = %g\n', x, cosX)

3/7
MATLAB Course UNIL-FGSE - Winter 2009-2010
III. Programming Principles - Solution
Auteur : Alexandre Loye

Réponses :

the function cos(210.3) = -1.564583

the Matlab function cos of 210 = -0.866025

the function cos(210.8) = -0.866023

the Matlab function cos of 210 = -0.866025

∞ n
• The function f(x) = excan be written in a Taylor series: ex= ∑ xn! .
n=0

Write a program that determines exby adding the terms of the Taylor series
until the absolute value of the last included term is < 10-4To do this, use the
while loop - limit the number of iterations to 20. If after 20 iterations, the
the incremented value is not less than 10-4, the program stops indicating a
message ( ex. ‘valeur eximprecise'). Give your answer for e3, e-4and e18.

the value x of the function exp(x)


x = input('enter the value x of the function exp(x) ')

define the terms of the Taylor series by looking at the first ones
%terms:
% exp(x) = 1 + x + x^2/2! + x^3/3!

the increment n, i.e. the number of terms, which starts at 1


n = 1;

set the sum of the function expX to 1, which is the sum of


first term

expX = 1;

define a variable for the next term n+1


%to start the while loop, the condition is that
%n_term >=0.0001

n_term = 0.0002; % 2 or 3 or 100…

use the while command to calculate the n-th term of the series
%et add it to the sum.

the condition is that the while loop is true as long as


The absolute value of the n-th term incremented is >= 0.0001 and the
%number of passages <= 20

while abs(n_term) >= 0.0001 & n <= 20


n_term = x^n/factorial(n)
expX = expX + n_term
n=n+1
end

4/7
MATLAB Course UNIL-FGSE - Winter 2009-2010
III. Programming Principles - Answer Key
Auteur : Alexandre Loye

%display an error message if more than 20 terms are needed


if n>=20
value exp(x) imprecise!
else
fprintf('exp(%g) with %g terms is %f ', x, n, expX)
end

Answer:

exp(3) with 15 terms is 20.085523

exp(-4) with 18 terms is 0.018307

for exp(18): imprecise value of exp(x)!

3. Conditions / loops
Create using a combination of loops and conditions the terrain profile as well as its
soil thickness below:

The coordinates of the land can be specified using the "for - end" structure.

Exercise:

• create in the form of a vector the coordinates in x and z and gather them under a
even using the structure "for - end" (see advice below!).

• Graphically represent your profile using the command:

5/7
MATLAB Course UNIL-FGSE – Winter 2009-2010
III. Programming Principles - Solution
Auteur : Alexandre Loye

figure
plot(xzdata(:,1), xzdata(:,2), '-r', 'LineWidth', 2)
axis([min(x) max(x) 0 30]);

• add the soil thickness profile according to two scenarios:

The thickness of the ground (normal to the ground) is 2 meters along its entire length.

The thickness of the soil is proportional to the slope, such that: S = soil thickness * cos(slope)

For this, it is advisable to discretize the x-axis (distance) in intervals of 1m and


to use the structure "for – end". The slope can be calculated using:

slope (X2-1) = atan((Z(2)-Z(1))/dx), or dx = the increment (1m)

% x-coord. axis of the cross-profile


x = [0 10 20 30 40 50 60 70 80 90 100];

z-coordinate: the elevation z such that z = f(x)


z = [25 25 25 25 25 15 5 5 5 5 5];

Transpose the row matrix x into a column matrix xx


% the same for z
xx = x';
zz = z';

% join the two matrices xx and zz together


xzdata = [xx zz];

% separate the xzdata matrices into two matrices xdata and zdata
%NB: when working with loops, it is sometimes
It is wise to preallocate memory to optimize speed.
% of calculation by declaring the variables in advance.

xdata = zeros(11,1);
zdata = zeros(11,1);

for i = 1:11
xdata(i) = xzdata(i,1);
zdata(i) = xzdata(i,2);
end

represent the elevation of the surface in a graph along


the x-axis
figure
%plot(xdata,zdata,'-r','LineWidth',2)
plot(xzdata(:,1), xzdata(:,2), '-r', 'LineWidth', 2)
axis([min(x) max(x) 0 30]);

Add the soil thickness profile


xmin = 0;
xmax = 100;

6/7
MATLAB Course UNIL-FGSE - Winter 2009-2010
III. Programming Principles - Solution
Auteur : Alexandre Loye

%x-coord. axis is 100m long for example, so that we can


create a soil thickness data point at every meter for example
imax = 101;

create the increment step along the x-coord axis


dx = xmax / (imax - 1);

Enter the thickness of the floor (normal to the floor)


soilthick = 2;

%create the x-coord


for i = 1:imax
X(i) = (i - 1)*dx;
end

calculate the elevation


for i = 1:41
Z(i) = 25;
end
for i = 42:61
Z(i) = Z(i-1) - 1;
end
for i = 62:imax
Z(i) = 5;
end

%calculate the thickness of the soil


for i = 1:imax
S(i) = Z(i) - soilthick;
end

graphical representation
figure
plot(X,Z,X,S,'LineWidth',1.5)
axis([xmin xmax 0 30])

the thickness of the riverbank soil is proportional to the slope


use the cos function of the slope

% calculation of the slope of the profile


slp = zeros(imax, 1);
for i = 1:imax-1
slp(i+1) = atan((Z(i+1)-Z(i))/dx);
%slp_deg(i) = slp(i)*180/pi;
end

Calculation of soil thickness


for i = 1:imax
Snew(i) = Z(i) - soilthick * cos(slp(i));
end

Graphic representation of the new soil thickness


figure
plot(X,Z,X,Snew,'LineWidth',1.5)
axis([xmin xmax 0 30])

7/7

You might also like