- Master MATLAB functions
Objective and Requirements of the Experiment
- Master the program flow of MATLAB
- Master the writing of MATLAB script and function files
- Familiar with matrix-based programming and optimization
Section Two: Experimental Principles
- MATLAB M files: script files and function files;
- MATLAB program flow: input, disp, if statement, for loop, while loop, switch-case structure, and try-catch structure;
- Function files, anonymous functions, functions within the file;
- MATLAB Program Design and Optimization: Vectorized design instead of loop statements, pre-defined variables, etc.;
Three, Experimental Instruments
100 PCs and MATLAB software
Section Four: Experimental Content and Steps
(1) Write a function to solve the roots of an equation (the values of a, b, c are determined by user input), requiring it to be able to judge the situation of the solution set and control the output of the function accordingly. Note: ① Prompt for input parameters (e.g., is the number of input parameters accurate? How should defaults be handled?) ② Print the situation of the solution on the screen ③ Finally, output the specific values of the solutions.
function [x1,x2] = solveEquation(a,b,c)
if nargin ~= 3
error('Error: Invalid number of input parameters. Please provide exactly 3 coefficients.')
end
if a == 0
error('Error: The equation is not a quadratic equation. Coefficient a cannot be zero.')
end
discriminant = b^2 - 4*a*c;
if discriminant > 0
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
disp('The equation has two real roots:')
disp(['x1 = ', num2str(x1)])
disp(['x2 = ', num2str(x2)])
else if discriminant == 0
x1 = -b / (2*a);
disp('This equation has one real root:')
disp(['x1 = ', num2str(x1)])
else
% discriminant < 0
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2*a);
disp('This equation has two real roots:')
disp(['x1 = ', num2str(realPart), ' + i', num2str(imagPart)])
disp(['x2 = ', num2str(realPart), ' - i', num2str(imagPart)])
end
end
Please provide the content you would like translated to English.
```matlab
clc, clear;
solveEquation(1, 3, 0);
Sure, please provide the content you would like translated to English.
## (2) Input a percentage score and output the grade level A+, A, B, C, D, E. Where 100 is A+, 90-99 is A, 80-89 is B, 70-79 is C, 60-69 is D, and below 60 is E. Requirements:
Implement using a switch statement;
② After entering the percentage score, it should be determined whether the score is reasonable. If the score is unreasonable, an error message should be output.
```matlab
function grade = calculateGrade(score)
Calculate the grade based on the percentage score.
if score < 0 || score > 100
Unreasonable grades
error('The entered score is invalid. Please enter a number between 0 and 100.');
else
Reasonable grades
switch (score / 10)
case 10
grade = 'A+';
case 9
grade = 'A';
case 8
grade = 'B';
case 7
grade = 'C';
Case 6
grade = 'D';
otherwise
grade = 'E';
end
end
end
Sure, please provide the content you would like translated to English.
```matlab
clc, clear;
score = input('Please enter the score in percentage: ');
grade = grades(score);
disp(['Grade: ', grade]);
Please provide the content you want to translate.
## (3) Find the second integer within a specified range that is divisible by n. For example, find the second integer in the range [200, 500] that is divisible by 32. Requirements:
1. Validate the input reasonableness; the input parameters must be positive integers. If not, re-enter until the input is an integer before proceeding to the next step.
② Write it as a function file, which allows flexible changes to the interval range and the value of integer n.
```matlab
function x = findSecondDivisibleNumberInRange(start, finish, n)
Find the second integer divisible by n within the specified range.
Check the rationality of input parameters
if nargin ~= 3 || ~isnumeric(start) || ~isnumeric(finish) || ~isnumeric(n) || ...
start <= 0 || finish <= 0 || n <= 0 || start > finish
error('Invalid input parameters. Please enter three positive integers, and ensure that start <= finish.');
end
Find the second integer that is divisible by n.
count = 0;
for x = start : finish
if x % n == 0
count = count + 1;
if count == 2
return;
end
end
end
No integer found that meets the criteria.
error('No second integer divisible by %d found in the specified range.', n);
end
Sure, please provide the content you would like translated to English.
```matlab
start = input('Please enter the starting value of the interval:');
finish = input('Please enter the end value of the interval:');
n = input('Please enter the value of integer n: ');
x = findSecondDivisibleNumberInRange(start, finish, n);
fprintf('The second integer divisible by %d in the range [%d, %d] is %d.\n', n, start, finish, x);
Sure, please provide the content you would like translated to English.
## (4) Calculate the approximate value of when respectively taking 100, 1000, and 10000. Implement using both loop statements and vectorized programming design. Note: Vectorization refers to utilizing matrix operations in MATLAB, which is faster than the loop process.
### Loop
```matlab
function approx = calculatePiApproximationLoop()
for n in [100, 1000, 10000]:
sum = 0;
for i = 1 : n
sum = sum + 1 / Math.pow(i, 2);
end
approx = sqrt(6 * sum);
fprintf('When n = %d, the approximation is %f.\n', n, approx);
end
end
Sure, please provide the content you would like translated to English.
Vector
```matlab
function approx = calculatePiApproximationVectorized()
for n = [100, 1000, 10000]
i = 1 : n;
s = sum(1 ./ i.^2);
approx = sqrt(6 * s);
fprintf('When n = %d, the approximation is %f.\n', n, approx);
end
end
Please provide the content you would like translated to English.
```matlab
approxLoop = calculatePiApproximationLoop();
approxVectorized = calculatePiApproximationVectorized();
The approximate value using the loop method is %f, and the approximate value using the vectorized method is %f.\n
Sure, please provide the content you would like translated to English.