Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Matlab 1 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Chương 1:

1. Find a format option that would result in the following output format:
>> 5/16 + 2/7
ans =
67/112
Giải:
>> format rat
>>5/16 + 2/7
ans= 67/112

2. The function sin calculates and returns the sine of an angle in radians, and the
function sind returns the sine of an angle in degrees. Verify that calling the sind
function and passing 90 degrees to it results in 1. What argument would you pass
to sin to obtain the result of 1?
Giải:
>> sin(pi/2)
ans= 1

3. The combined resistance RT of three resistors R1, R2, and R3 in parallel is given by
Create variables for the three resistors and store values in each, and then calculate the
combined resistance.
Giải:
>>R1=2;
>>R2=3;
>>R3=4;
>>RT=1/(1/R1+1/R2+1/R3)
RT = 12/13

4. Use help elfun or experiment to answer the following questions.


n Is fix(3.5) the same as floor(3.5)?
n Is fix(3.4) the same as fix(-3.4)?
n Is fix(3.2) the same as floor(3.2)?
n Is fix(-3.2) the same as floor(-3.2)?
n Is fix(-3.2) the same as ceil(-3.2)?
Giải:
>>fix(3.5)
ans= 3
>>floor(3.5)
ans= 3
suy ra fix(3.5) giống floor(3.5)
>>fix(3.4)
ans= 3
>>fix(-3.4)
ans= -3
suy ra fix(3.4) khác fix(-3.4)
>>fix(3.2)
ans= 3
>>floor(3.2)
ans= 3 suy ra fix(3.2) giống floor(3.2)
>>fix(-3.2)
ans= -3
>>floor(-3,2)
ans= -4
suy ra fix(-3.2) khác floor(-3.2)
>>fix(-3.2)
ans= -3
>>ceil(-3.2) ho
ans= -3
suy ra fix(-3.2) giống ceil(-3.2)

5. For what range of values is the function round equivalent to the function floor?
For what range of values is the function round equivalent to the function ceil?
Giải:
+> Hàm floar: - Sổ dương khi số thập phân bé hơn 5

- Số âm khi số ở hàng thập phân lớn hơn hoặc bằng 5


+> Hàm Ceil: - Số dương khi số ở hàng thập phân lớn hơn bằng 5

- Số âm khi số ở hàng thập phân nhỏ hơn 5

6. Use help to determine the difference between the rem and mod functions.
Giải:
Rem:
>>help rem
rem remainder after division
rem(x,y) is x-n*y where n= fix(x/y) if y ~=0
Mod:
>>held mod
Mod Modulus after division
mod(x;y) is x-n*y where n = floor(x/y) if u ~=0

7. Find MATLAB expressions for the following


căn(19)
3^12
tan(p)
Giải:
>>sprt(19)
ans= 1421/326
>>3^12
ans= 531441
>>tan(Pi)
ans= -1/8165619676597

8. Generate a random
n real number in the range (0, 20)
n real number in the range (20, 50)
n integer in the inclusive range from 1 to 10
n integer in the inclusive range from 0 to 10
n integer in the inclusive range from 50 to 100.

9. What would be the result of the following expressions?


'b' >= 'c' - 1
3 == 2 + 1
(3 == 2) + 1
xor(5 < 6, 8 > 4)
Giải:
>> ‘b’= ‘c’ -1
ans= 1
>> 3 == 2 + 1
ans= 1
>>(3==2) + 1
ans= 1
>>xor (5<6, 8>4)
ans = 2

10. A vector can be represented by its rectangular coordinates x and y or by its polar
coordinates r and q. The relationship between them is given by the equations:
x = r * cos(q)
y = r * sin(q)
Giải:
>> r=2;
>> theta=0,5;
>> x=r*cos(theta)
x = 1.7552
>>y =r*sin(theta)
y = 09589

Chương 2:
1. Generate a 2x4 matrix variable mat. Replace the first row with 1:4. Replace the
third column (you decide with which values).

ĐA:
>>mat=[2:5; 1 4 11 3]
mat =
2 3 4 5
1 4 11 3
>>mat(1,:)=1:4
mat =
1 2 3 4
1 4 11 3
>>mat(:,3)=[6;7]
mat =
1 2 6 4
1 4 7 3

2. Generate a 2x3 matrix of random


n real numbers, each in the range (0, 1)
n real numbers, each in the range (0, 10)
n integers, each in the inclusive range from 5 to 20.

ĐA:
>> rand(2,3)
ans =
0.8147 0.1270 0.6324
0.9058 0.9134 0.0975

>> rand(2,3)*10
ans =
2.7850 9.5751 1.5761
5.4688 9.6489 9.7059
>> randi([5,20],2,3)
ans =
20 17 11
12 7 19
3. Create a variable rows that is a random integer in the inclusive range from 1 to 5.
Create a variable cols that is a random integer in the inclusive range from 1 to 5.
Create a matrix of all zeros with the dimensions given by the values of rows and
cols.
ĐA:
>> rows=randi([1,5])
rows =
5
>> cols=randi([1,5])
cols =
4
>> zeros(rows,cols)
ans =

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

4. The built-in function clock returns a vector that contains six elements: the first
three are the current date (year, month, day) and the last three represent the current
time in hours, minutes, and seconds. The seconds is a real number, but all others are
integers. Store the result from clock in a variable called myc. Then, store the first
three elements from this variable in a variable today and the last three elements in a
variable now. Use the fix function on the vector variable now to get just the integer
part of the current time.
ĐA:
>> myc=clock
myc =
1.0e+03 *
2.0200 0.0070 0.0150 0.0140 0.0430 0.0066
>> today=myc(1:3)
today =
2020 7 15
>> now=myc(4:end)
now =
14.0000 43.0000 6.6090
>> fix(now)
ans =
14 43 6
5. Create a 3x5 matrix of random real numbers. Delete the third row.
ĐA:
>> mat=rand(3,5)
mat =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003

>> mat(3,:)=[]
mat =
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
6. Create a vector x which consists of 20 equally spaced points in the range from -(pi)
to +(pi). Create a y vector which is sin(x)
DA:
>> x=linspace(0.2*pi,20);
y=sin(x)
( Ấn enter sẽ ra một loạt giá trị )
7. Find the sum of the first n terms of the harmonic series where n is an integer
greater than one.

ĐA:
>> n = 5;
mauSo = 1:n
v = 1./mauSo
sum(v)
mauSo =
1 2 3 4 5
v =
1.0000 0.5000 0.3333 0.2500 0.2000
ans =
2.2833
8. Find the sum of the first five terms of the geometric series

ĐA:
n = 5;
soMu =0:n-1
mauSo =2.^soMu
v = 1./mauSo
sum(v)
9. Find the following sum by first creating vectors for the numerators and

denominators:

ĐA:
tuSo = 3:2:9
mauSo = 1:4
v = tuSo./mauSo
sum(v)
10. Create a vector of five random integers, each in the inclusive range from e10 to 10.
Perform each of the following:
n subtract 3 from each element
n count how many are positive
n get the absolute value of each element
ĐA:
>> vec=randi([-10;10],1,5)
vec =
3 -10 7 9 4
>> vec-3
ans =
0 -13 4 6 1
>> abs(vec)
ans =
3 10 7 9 4
>> max(vec)
ans =
9
11. Create a 3x5 matrix. Perform each of the following:
n Find the maximum value in each column.
n Find the maximum value in each row.
n Find the maximum value in the entire matrix.
DA:
m = randi([10 100],3,5)
max(m)
max(m')
max(max(m))
12. The value of pi^2/6 can be approximated by the sum of the series

ĐA:
n = 4;
sum(1./(3.^(0:n-1)))
13. For the following matrices A, B, and C:

 n give the result of 3*A

 n give the result of A*C

 n Are there any other matrix multiplications that can be performed? If so, list
them.
ĐA:
A = [4 1 -1; 2 3 0];
B = [1 4];
C = [2; 3];
n = 3*A
m = A*C
fprintf('Co 3 phep nhan ma tran co the đuoc thuc hien');
a = C*B
b = B*C
c = B*A
14. Evaluate the function f of two variables x and y, where x ranges from 1 to 2 and y
ranges from 1 to 5.
f(x,y) = 3*x - y
ĐA:
[x y] = meshgrid(1:2,1:5);
fx = 3*x-y
15. A company is calibrating some measuring instrumentation and has measured the radius
and height of one cylinder 10 separate times; they are in vector variables r and h. Find
the volume from each trial, which is given by pir^2h. Also use logical indexing first to
make sure that all measurements were valid (> 0).
ĐA:
r = 5 + rand(1,10)/10;
h = 6 + rand(1,10)/10;
r(5) = -2;
h(8) = -4;
rad = r(h>0 & r>0);
hei = h(h>0 & r>0);
vol = pi.*(rad.^2).*hei
16. For the following matrices A, B, and C:

 n give the result of 3*A

 n give the result of A*C

 n Are there any other matrix multiplications that can be performed? If so, list
them.
ĐA:
A = [1 4; 3 2];
B = [2 1 3; 1 5 6; 3 6 0];
C = [3 2 5; 4 1 2];
n = 3*A
m = A*C
fprintf('Co 1 phep nhan ma tran co the duoc thuc hien');
a = C*B
17. The matrix variable rainmat stores the total rainfall in inches for some districts
for the years 2010e2013. Each row has the rainfall amounts for a given district. For
example, if rainmat has the value:
>> rainmat
ans =
25 33 29 42
53 44 40 56
etc.
district 1 had 25 inches in 2010, 33 in 2011, etc. Write expression(s) that will find the
number of the district that had the highest total rainfall for the entire four-year
period.
ĐA:
rainmat = [25 33 29 42; 53 44 40 56];
max(sum(rainmat))

18. Create a vector variable vec; it can have any length. Then, write assignment

statements that would store the first half of the vector in one variable and the

second half in another. Make sure that your assignment statements are general,

and work whether vec has an even or odd number of elements. (Hint: use

a rounding function, such as fix.) Some operations are easier to do if a matrix (in particular, if it is really large) is parti-
tioned into blocks. Partitioning into blocks also allows utilization of grid computing or parallel computing, where the
operations are spread over a grid of computers. For example, if

it can be partitioned into where

If B is the same size, Partition it

into

ĐA:
vec = 1:9;

fhalf = vec(1:fix(length(vec)/2))

shalf = vec(fix(length(vec)/2+1:end))

37. For the following vectors and matrices A, B, and C:

Perform the following operations, if possible. If not, just say it can’t be done!

A*B

B*C

C*B

ĐA:

A = [4 1 -1; 2 3 0];

B = [1 4];

C = [2; 3];

fprintf('A*B khong tinh duoc');

m = B*C

n = C*B

Chương 3:
1. If the lengths of two sides of a triangle and the angle between them are known,
thelength of the third side can be calculated. Given the lengths of two sides (b and c)
of a triangle, and the angle between them a in degrees, the third side a is calculated as
follows:
a2 1⁄4 b2 þ c2 e 2 b c cos(a)
Write a script thirdside that will prompt the user and read in values for b, c, and a (in
degrees), and then calculate and print the value of a with three decimal places. The
format of the output from the script should look exactly like this:
>> thirdside
Enter the first side: 2.2
Enter the second side: 4.4
Enter the angle between them: 50
The third side is 3.429
For more practice, write a function to calculate the third side, so the script will call
this function.

ĐA :
function Chuong03_10()
clear
clc
b = input(' Enter the first side ');
c = input(' Enter the second side: ');
alpha = input(' Enter the angle between them ');
a = thirdSide(b, c, alpha);
fprintf(' The third side is’, a);
end

function a = thirdSide(b, c, alpha)


a = sqrt(b^2 + c^2 - 2*b*c*cosd(alpha));
end

2. Write a script lumin that will calculate and print the luminosity L of a star in
Watts. The luminosity L is given by L=4 π d 2 b ,, where d is the distance from the sun in
meters and b is the brightness in Watts/meters2.Here is an example of executing the
script:
>> lumin
This script will calculate the luminosity of a star.
When prompted, enter the star's distance from the sun
in meters, and its brightness in W/meters squared.
Enter the distance: 1.26e12
Enter the brightness: 2e-17
The luminosity of this star is 399007399.75 watts

ĐA:
function chuong03_12()
clear
clc
fprintf('This script will calculate the luminosity of a star.\n');
fprintf('When prompted, enter the star''s distance from the sun\n');
fprintf('in meters, and its brightness in W/meters squared.\n\n');
d = input('Enter the distance: ');
b = input('Enter the brightness:');
L = lumin(d,b);
fprintf('The luminosity of this star is %.2f watts\n',L);
end
function L = lumin(d,b)
L = 4*pi*d*b;
end
3 In engineering mechanics, a vector is a set of numbers that indicate both magnitude and direction.
Units such as velocity and force are vector quantities. An example of a vector could be <2.34, 4.244,
5.323> meters/second. This vector describes the velocity of a particle at a certain point in three-
dimensional space, <x,y,z>. In solving problems related to vectors, it’s handy to know the unit vector of a
certain measurement. A unit vector is a vector that has a certain direction, but a magnitude of 1. The
equation for a unit vector in three-dimensional space is:
u⃗ =¿ x , y , z > 2 ¿ 2 2 ¿
√ x + y +z
Write a script that prompts the user for x, y, and z values, and then calculates the unit vector.
ĐA:
function chuong3_13 ()
clear
clc
v = input('Nhap vector v: ');
L = sqrt(dot(v,v));
fprintf('L truoc khi chuan hoa: %.4f\n', L)'

v = v / L;

fprintf('v da chuan hoa = [');


fprintf('%.4f', v(1:2));
fprintf('%.4f]\n', v(3));

L = sqrt(dot(v,v));
fprintf('L sau khi chuan hoa: %.4f\n', L)';
end

17) Generate a random integer n, create a vector of the integers 1 through n in steps of 2, square them,
and plot the squares.
ĐA:
function chuong3_17()
clear
clc
n = randi([1,50]);
vec = 1:2:n;
vecsq = vec.^2;
plot(vecsq,'k*');
title('squares of integers');
end

18) Create a 3 x 6 matrix of random integers, each in the range from 50 to 100. Write this to a file called
randfile.dat. Then, create a new matrix of random integers, but this time make it a 2 x 6 matrix of
random integers, each in the range from 50 to 100. Append this matrix to the original file. Then, read the
file in (which will be to a variable called randfile) just to make sure that worked!
ĐA:
function chuong03_18()
clear
clc
mat = randi([50,100],3,6);
save randfile.dat mat -ascii ;
newmat = randi([50,100],2,6);
save randfile.dat newmat -ascii -append;
end
19) In hydrology, hyetographs are used to display rainfall intensity during a storm. The intensity could be the
amount of rain per hour, recorded every hour for a 24-hour period. Create your own data file to store the
intensity in inches per hour every hour for 24 hours. Use a bar chart to display the intensities.
ĐA:
function chuong3_19()
time = (1:24);
rain = rand(1,24);
bar(time,rain);
xlabel('Hour');
title('hyetographs');
end
21) A file “floatnums.dat” has been created for use in an experiment. However, it contains float (real)
numbers and what is desired instead is integers. Also, the file is not exactly in the correct format; the
values are stored columnwise rather than rowwise. For example, if the file contains the following:
90.5792 27.8498 97.0593
12.6987 54.6882 95.7167
91.3376 95.7507 48.5376
63.2359 96.4889 80.0280
9.7540 15.7613 14.1886
what is really desired is:
91 13 91 63 10
28 55 96 96 16
97 96 49 80 14
Create the data file in the specified format. Write a script that would read from the
file floatnums.dat into a matrix, round the numbers, and write the matrix in the
desired format to a new file called intnums.dat.
ĐA:
function chuong3_21()
clear
clc
load floatnums.dat
inums = round(floatnums)';
save intnums.dat inums -ascii
end

23) A file called “hightemp.dat” was created some time ago, which stores, on every line, a year followed
by the high temperature at a specific site for each month of that year. For example, the file might look
like this:

1989 42 49 55 72 63 68 77 82 76 67
1990 45 50 56 59 62 68 75 77 75 66
1991 44 43 60 60 60 65 69 74 70 70
etc.

As can be seen, only two digits were used for the year (which was common in the last century). Write a
script that will read this file into a matrix, create a new matrix which stores the years correctly as 19xx,
and then write this to a new file called “y2ktemp.dat”. (Hint: add 1900 to the entire first column of the
matrix.) Such a file, for example, would look like this:

89 42 49 55 72 63 68 77 82 76 67
90 45 50 56 59 62 68 75 77 75 66
91 44 43 60 60 60 65 69 74 70 70
ĐA:
function chuong3_23()
clear
clc
load hightemp.dat;
hightemp(:,1)= hightemp(:,1)+1900;
save y2ktemp.dat hightemp -ascii;
end
25) Write a function perim that receives the radius r of a circle, and calculates and returns the perimeter
P of the circle ( P=2 πr ¿. Here are examples of using the function:
>> perimeter = perim(5.3)
perimeter =
33.3009
>> fprintf('The perimeter is %.1f\n', perim(4))
The perimeter is 25.1
>> help perim
Calculates the perimeter of a circle
ĐA:
function chuong03_25()
clear
clc
r = input('nhap ban kinh: ');
P = perim(r);
fprintf('chu vi hinh tron la: %.1f\n',P);
end

function chuvi = perim(bankinh)


chuvi = 2*pi*bankinh;
end
30) Write a fives function that will receive two arguments for the number of rows and columns, and will return
a matrix with that size of all fives.
ĐA:
function chuong3_30()
clc
clear
r=input('Enter the value of rows: ');
c=input('Enter the value of colums: ');
matrix = fives(r,c)
end

function five = fives(rows,cols)


five = zeros(rows,cols) + 5;
end

31) Write a function isdivby4 that will receive an integer input argument, and will return logical 1 for
true if the input argument is divisible by 4 or logical false if it is not.
ĐA:
function chuong03_31()
clear
clc
a = input('nhap so nguyen: ');
result = isdivby4(a);
fprintf('ket qua la: %d\n', result);
end
function result = isdivby4(a)
result = rem(a,4)==0;
end
33) A Pythagorean triple is a set of positive integers (a, b, c) such that a 2+ b2=c 2. Write a function
ispythag that will receive three positive integers (a, b, c - in that order) and will return logical 1 for true if
they form a Pythagorean triple or 0 for false if not.
ĐA:
function chuong3_33()
clear
clc
a = input('nhap a: ');
b = input('nhap b: ');
c = input('nhap c: ');
result = ispythag(a, b ,c);
fprintf(' kq la: %d\n', result);
end

function result = ispythag(soA, soB, soC)


result = soA^2 + soB^2 == soC^2;
end

34) A function can return a vector as a result. Write a function vecout that will receive one integer
argument and will return a vector that increments from the value of the input argument to its value plus
5, using the colon operator. For example,
>> vecout(4)
ans =
456789
ĐA:
function chuong3_34()
clc
clear
n = input('Enter the value of first argument: ');
vecout = vecout(n);
end

function vecout=vecout(n)
vecout = [n:(n+5)] ;
end

35) Write a function repvec that receives a vector and the number of times each element is to be
duplicated. The function should then return the resulting vector. Do this problem using built-in functions
only. Here are some examples of calling the function:
>> repvec(5:-1:1,2)
ans =
5544332211
>> repvec([0 1 0],3)
ans =
000111000
ĐA:
function chuong3_35()
clear
clc
v = input('nhap vector v: ');
m = input('nhap so lan lap m: ');
x = repmat(v,m,1);
x = reshape(x,1,length(v)*m);
fprintf('x = ');
fprintf('%d ', x);
fprintf('\n');
end
36) Write a function that is called pickone, which will receive one input argument x, which is a vector,
and will return one random element from the vector. For example,
>> disp(pickone(-2:0))
-1
>> help pickone
pickone(x) returns a random element from vector x
ĐA:
function chuong3_36()
clear
clc
v = input('nhap vector v: ');
x = pickone(v);
fprintf('phan tu bat ky trong vector v la: %d\n' , x);
end

function kq = pickone(vector)
L = length(vector);
n = randi([1 L]);
kq = vector(n);
end
37) The cost of manufacturing n units (where n is an integer) of a particular product at a factory is given
by the equation:
2
C ( n )=5 n −44 n+11
Write a script mfgcost that will:
+ prompt the user for the number of units n
+ call a function costn that will calculate and return the cost of manufacturing n units
+ print the result (the format must be exactly as shown below).
Next, write the function costn, which simply receives the value of n as an input
argument, and calculates and returns the cost of manufacturing n units.
Here is an example of executing the script:
>> mfgcost
Enter the number of units: 100
The cost for 100 units will be $45611.00
ĐA:
function chuong3_37()
clear
clc
n = input('Enter the numbers of unit: ');
C = 5*n^2 - 44*n +11 ;
fprintf('The cost for %d units will be $%.2f\n',n,C);
end

42) A file called costssales.dat stores for a company some cost and sales figures for the last n quarters (n
is not defined ahead of time). The costs are in the first column and the sales are in the second column. For
example, if five quarters were represented, there would be five lines in the file, and it might look like this:
1100 800
1233 650
1111 1001
1222 1300
999 1221
Write a script called salescosts that will read the data from this file into a matrix. When the script is
executed it will do three things. First, it will print how many quarters were represented in the file, such
as:
>> salescosts
There were 5 quarters in the file Next, it will plot the costs using black circles and sales using black stars
(*) ina Figure Window with a legend (using default axes), as seen in Figure 3.9. Finally, the script will
write the data to a new file called newfile.dat in a different order. The sales will be the first row and the
costs will be the second row. For example, if the file is as shown above, the resulting file will store the
following:
800 650 1 001 1300 1221
1100 1233 1111 1222 999
It should not be assumed that the number of lines in the file is known.
ĐA:
function chuong3_42()
clear
clc
clf
% yeu cau 1
load costssales.dat
m = length(costssales);
fprintf('Co %d quarters trong file\n', m );
% yeu cau 2
costssales = costssales';
hold all
plot(costssales(1,:), 'ko');
plot(costssales(2,:), 'k*');
xlabel('Quarter');
title('company costs and sales');
legend('costs','sales');
%yeu cau 3
m = flipud(costssales);
save newfile.dat m -ascii;
end

BÀI TẬP CHƯƠNG 4


3. Write a script to calculate the volume of a pyramid, which is 1/3 * base * height, where the
base is length * width. Prompt the user to enter values for the length, width, and height, and then
calculate the volume of the pyramid. When the user enters each value, he or she will then also be
prompted for either ‘i’ for inches or ‘c’ for centimeters. (Note that 2.54 cm 1⁄4 1 inch.) The script
should print the volume
in cubic inches with three decimal places. As an example, the output format will be:

This program will calculate the volume of a pyramid.


Enter the length of the base: 50
Is that i or c? i
Enter the width of the base: 6
Is that i or c? c
Enter the height: 4
Is that i or c? i
The volume of the pyramid is xxx.xxx cubic inches.
Giải
function Bai3()
clear
clc
% Goi a,b,h lan luot la chieu dai, chieu rong, chieu cao cua pyramid
a = input('Nhap chieu dai: ');
units_a = input('Don vi la i or c? ','s');
if units_a == 'c'
a = a/2.54;
elseif units_a == 'i'
a = a;
else
fprintf('Nhap sai don vi !\n');
return
end
b = input('Nhap chieu rong: ');
units_b = input('Don vi la i or c? ','s');
if units_b == 'c'
b = b/2.54;
elseif units_b == 'i'
b = b;
else
fprintf('Nhap sai don vi !\n');
return
end
h = input('Nhap chieu cao: ');
units_h = input('Don vi la i or c? ','s');
if units_h == 'c'
h = h/2.54;
elseif units_h == 'i'
h = h;
else
fprintf('Nhap sai don vi !\n');
return
end
V = a*b*h/3;
fprintf('The tich cua kim tu thap la %.4f\n', V);
end
5. The Pythagorean theorem states that for a right triangle, the relationship betweenthe length of
the hypotenuse c and the lengths of the other sides a and b is given by:
Write a script that will prompt the user for the lengths a and c, call a function findb to calculate
and return the length of b, and print the result. Note that any values of a or c that are less than or
equal to zero would not make sense, so the script should print an error message if the user enters
any invalid value. Here is the function findb:
Giải
function Bai05()
clear
clc
a = input('Nhap canh goc vuong thu 1: ');
c = input('Nhap canh huyen: ');
b = finb(a,c);
if a > 0 && c > 0
b = finb(a,c);
fprintf('Canh goc vuong thu 2 la: %d\n', b);
else
fprintf('Khong ton tai\n');
end
end
function b = finb(a,c)
b = sqrt(c^2-a^2);
end

6. The eccentricity of an ellipse is defined as


where a is the semimajor axis and b is the semiminor axis of the ellipse. A script prompts the user
for the values of a and b. As division by 0 is not possible, the script prints an error message if the
value of a is 0 (it ignores any other errors, however). If a is not 0, the script calls a function to
calculate and returns the eccentricity, and then the script prints the result. Write the script and
the function.

Giải
function Bai06()
clear
clc
a = input('Nhap truc dai: ');
b = input('Nhap truc ngan: ');
x = sqrt(1-(b/a)^2);
if a > 0
x = sqrt(1-(b/a)^2);
fprintf('Do lech tam cua elip la:%.2f\n', x);
else
fprintf('Khong ton tai');
end
end

7. The area A of a rhombus is defined as , where d1 and d2 are the lengths of the two
diagonals. Write a script rhomb that first prompts the user for the lengths of the two diagonals.
If either is a negative number or zero, the script prints an error message. Otherwise, if they are
both positive, it calls a function rhombarea to return the area of the rhombus, and prints the
result. Write the function, also! The lengths of the diagonals, which you can assume are in inches,
are passed to the rhombarea function.
Giai
function Bai07()
clear
clc
d1 = input('Nhap truc 1: ');
d2 = input('Nhap truc 2: ');
A = rhombarea(d1,d2);
if d1 > 0 && d2 > 0
A = rhombarea(d1,d2);
fprintf('Dien tich hinh thoi la:%.2f\n', A);
else
fprintf('Khong ton tai');
end
end
function A = rhombarea(d1,d2)
A = d1*d2/2;
end

8. Simplify this statement:


if number > 100
number = 100;
else
number = number;
end
Giải
if number > 100
number =100;
end

9. Simplify this statement:


if val >= 10
disp('Hello')
elseif val < 10
disp('Hi')
end
Giải
if val >= 10

disp('Hello')
else

disp('Hi')
end
10. Write a function createvecMToN that will create and return a vector of integers
from m to n (where m is the first input argument and n is the second), regardless of
whether m is less than n or greater than n. If m is equal to n, the “vector” will just
be 1x1 or a scalar.
Giải
function result = createvecMtoN(m,n)
clear
clc
m = input('Nhap m: ');
n = input('Nhap n: ');
if m > n
result = m : -1 : n
elseif m == n
result = m;
else
result =m : 1: n
end

13. Write a function flipvec that will receive one input argument. If the input argument
is a row vector, the function will reverse the order and return a new row vector. If
the input argument is a column vector, the function will reverse the order and
return a new column vector. If the input argument is a matrix or a scalar, the
function will return the input argument unchanged.
Giải
function C4_Bai13()
clear
clc
m = input('Nhap ma tran m: ');
m = flipvec(m);
fprintf('m =\n');
disp(m);
end
function result = flipvec(matrix)
[r, c] = size(matrix);
if r == 1 && c > 1
result = fliplr(matrix);
elseif c == 1 && r > 1
result = flipud(matrix);
else
matrix = matrix;
end
end
17. Write a script that will prompt the user for a temperature in degrees Celsius, and
then an ‘F’ for Fahrenheit or ‘K’ for Kelvin. The script will print the corresponding
temperature in the scale specified by the user. For example, the output might
look like this:
Enter the temp in degrees C: 29.3
Do you want K or F? F
The temp in degrees F is 84.7
The format of the output should be exactly as specified above. The conversions are:

Giải
function C4_Bai17()
clear
clc
x = input('Nhap nhiet do C: ');
y = input('Doi thanh K hay F? ','s');
switch y
case 'K'
x = x + 273.15;
fprintf('Nhiet do o do K la: %.2f\n', x);
case 'F'
x = x*9/5 + 32;
fprintf('Nhiet do o do F la: %.2f\n', x);
otherwise
fprintf('Nhap sai don vi !\n');
end
end
18. Write a script that will generate one random integer and will print whether
the random integer is an even or an odd number. (Hint: an even number is
divisible by 2, whereas an odd number is not; so check the remainder after
dividing by 2.)
Giải

function C4_Bai18()
clear
clc
x = randi(1000,1);
y = ~mod(x,2);
if y == 1
fprintf('So tu nhien %d la so chan\n', x);
elseif y == 0
fprintf('So tu nhien %d la so le\n', x);
end
end
22. Clouds are generally classified as high, middle, or low level. The height of the cloud is the
determining factor, but the ranges vary depending on the temperature. For example, in tropical
regions the classifications may be based on the following height ranges (given in feet):
low 0 - 6500
middle 6500 - 20,000
high > 20,000
Write a script that will prompt the user for the height of the cloud in feet and print
the classification.
Giải
function C4_Bai22()
clear
clc
x = input('Nhap chieu cao cua dam may tinh bang feet: ');
if x > 0 && x < 6500
fprintf('Dam may thuoc cap thap');
elseif x < 20000
fprintf('Dam may thuoc cap trung binh');
else
fprintf('Dam may thuoc cap cao');
end
fprintf('\n');
end

23. The Beaufort Wind Scale is used to characterize the strength of winds. The scale
uses integer values and goes from a force of 0, which is no wind, up to 12, which is
a hurricane. The following script first generates a random force value. Then, it
prints a message regarding what type of wind that force represents, using
a switch statement. You are to re-write this switch statement as one nested
if-else statement that accomplishes exactly the same thing. You may use else
and/or elseif clauses.
ranforce = randi([0, 12]);
switch ranforce
case 0
disp('There is no wind')
case {1,2,3,4,5,6}
disp('There is a breeze')
case {7,8,9}
disp('This is a gale')
case {10,11}
disp('It is a storm')
case 12
disp('Hello, Hurricane!')
end
Giải
function C4_Bai23()
clear
clc
x = randi([0. 12]);
if x == 0
disp('Khong co gio');
elseif 0 < x < 7
disp('Co mot lan gio');
elseif 6 < x < 10
disp('Day la mot con gio');
elseif 9 < x < 12
disp('Do la mot con bao');
else
disp('Xin chao, con bao!');
end
end
24. Re-write the following nested if-else statement as a switch statement that
accomplishes exactly the same result for all possible values. Assume that val is
an integer variable that has been initialized, and that “ok”, “xx”, “yy”, “tt”, and
“mid” are functions. Write the switch statement in the most succinct way.
Giải
function C4_Bai24()
clear
clc
val = randi([0. 10]);
if val > 5
if val < 7
ok(val)
elseif val < 9
xx(val)
else
yy(val)
end
else
if val < 3
yy(val)
elseif val == 3
tt(val)
else
mid(val)
end
end
end
27. Write a script areaMenu that will print a list consisting of “cylinder”, “circle”, and
“rectangle”. It prompts the user to choose one, and then prompts the user for the appropriate
quantities (e.g., the radius of the circle) and then prints its area. If the user enters an invalid
choice, the script simply prints an error message. The script should use a nested if-else statement
to accomplish this. Here are two examples of running it (units are assumed to be inches).
Giải
function C4_Bai27()
while true
clear
clc
fprintf('Tinh dien tich cac hinh sau:\n');
fprintf('1.Hinh tru\n');
fprintf('2.Hinh tron\n');
fprintf('3.Hinh chu nhat\n');
fprintf('0.Ket thuc\n');
BanChon = input('Ban Chon: ');
if BanChon == 0
break;
end
if BanChon == 1
r = input('Nhap ban kinh r: ');
h = input('Nhap do cao h: ');
a = 2*r*pi*h;
fprintf('Dien tich cua hinh tru la: %.2f\n', a);
end
if BanChon == 2
r = input('Nhap ban kinh r: ');
a = r*r*pi;
fprintf('Dien tich cua hinh tron la: %.2f\n', a);
end
if BanChon == 3
L = input('Nhap chieu dai L: ');
W = input('Nhap chieu rong W: ');
a = L*W;
fprintf('Dien tich cua hinh chu nhat la: %.2f\n', a);
end
fprintf('Nhan mot phim bat ki de tiep tuc...')
pause
end
end
35. Write a function called makemat that will receive two row vectors as input
arguments; from them create and return a matrix with two rows. You may not
assume that the length of the vectors is known. Also, the vectors may be of
different lengths. If that is the case, add 0’s to the end of one vector first to make it
as long as the other. For example, a call to the function might be:
Giải
function C4_Bai35()
clear
clc
a = input('Nhap vector thu nhat: ');
b = input('Nhap vector thu hai: ');
m = makemat(a, b);
fprintf('m =\n');
disp(m);
end
function result = makemat(v1,v2)
L1 = length(v1);
L2 = length(v2);
if L1 > L2
v2 = [v2 zeros(1,L1-L2)];
elseif L2 > L1
v1 = [v1 zeros(1,L2-L1)];
end
result = [v1; v2];
end

You might also like