|
本帖最后由 hbghlyj 于 2021-10-27 17:25 编辑 抄一下手册的附录B,可能对于1#的问题有帮助:
B.1 MATLAB “handle” functions and anonymous functions
We have seen that functions can be created using .m files (Section 4.3). You can create function handles using “anonymous functions”. This is most helpful for making a short function, for example:
>> alpha = 0.5
>> y = @(x) sin(alpha*x)
>> y(pi)
You can also create these sorts of functions from symbolic expressions:
>> syms x
>> y = sin(x)
>> ym = matlabFunction(y)
See help function_handle and help matlabFunction for more information.
B.2 Variable precision arithmetic
“Out-of-the-box” MATLAB focuses on supporting double precision floating point (the double class). Recall this class represents numbers using a precision of roughly 15 decimal digits. The Symbolic Math Toolbox (based on MuPAD) adds support for symbolic expressions (using the sym and symfun classes). The Symbolic Math Toolbox also adds support for Variable Precision Arithmetic via the vpa class. Having floating point numbers with more than 15 digits can be a useful feature and so this chapter is essentially for your own interest or reference.
To use variable precision arithmetic, first set the desired precision. Then use vpa() or a quoted symbolic constructor with a decimal place.
>> digits(64)
>> a = vpa(2/3)
>> b = sym('2.0')/3
Note that b = sym(2.0)/3 won’t work (why not?). Probably the vpa() command is less prone to accidental unwanted use.
It is worth noting that the clear command does not reset digits to its default value. But clear all will.
Exercise 6.1 All rational numbers p/q, where p and q are integers (q≠0), have a terminating or (eventually) repeating decimal form. By increasing the precision using digits() as appropriate, find the exact decimal form of 21/23.
Exercise 6.2 The following two expressions are both approximations to $π$ that were discovered by the Indian mathematician Ramanujan (1887–1920):$$\pi_{1}=\frac{12}{\sqrt{190}} \ln ((2 \sqrt{2}+\sqrt{10})(3+\sqrt{10}))$$and$$\pi_{2}=\sqrt{\sqrt{9^{2}+\frac{19^{2}}{22}}}$$Use VPA to find the absolute errors $|π_1 − π|$ and $|π_2 − π|$. Hence determine how good these approximations actually are.$\square$
B.3 Cell Arrays
Recall that a vector in MATLAB is homogeneous: everything inside it must be the same type (double, sym, etc). How dull! Cell arrays on the other hand can store anything, even other cell arrays. Make one like this:
>> A = {'Freedom!', sym(2/3), rand(3,3)}
>> A{1}
>> A{2}
>> A{3}
A common use of cell arrays is to store a “list of strings”. This is because an array of strings just concatenates them. For example:
>> L = ['red' 'lorry' 'yellow' 'lorry']
>> % output is 'redlorryyellowlorry'
>> S = {'red' 'lorry' 'yellow' 'lorry'}
>> % output is a 4-element cell array
This is useful for constructing legends for plots when using loops. |
|