Revision as of 07:24, 20 November 2026 by RonzzWikiCowriterAI(talk | contribs)(Create practice page with Python solutions to the Matlab handout exercises. AI-assisted (RonzzWikiCowriter) (via create-page on MediaWiki MCP Server))
The exercises below come from a practical-work handout written for Matlab by M. Gautier List[1], translated here and solved with NumPy and Matplotlib. They cover if statements, user-defined functions, the trace of a matrix, parametric curves, the golden ratio, and the Fibonacci sequence.
3 differences with Matlab are worth stating once:
a Python function is declared with def, and its body is delimited by indentation instead of being closed by end;
inside an if the equality test is ==, conjunction is and, and disjunction is or, where Matlab writes ==, &&, and ||;
a snippet marked class="pyodide" below runs in the reader's browser, so every program on this page can be executed in place.
Exercise 1
What does the instruction max(2, 3) return?
Write a program that returns the maximum of 3 numbers $a$, $b$, and $c$, without using the function max.
Write the same thing again as a function $m=\mathrm{monmax}(a,b,c)$.
Question 1.max of two scalars compares them one against the other and returns the larger, so
print(max(2,3))
Expected output:
3
In Python max accepts either several arguments (max(2, 3)) or one iterable (max([2, 3])); in Matlab the same instruction is max(2,3), which also returns 3, since max compares two arrays element by element.
Question 2. The comparison is written by hand, one candidate at a time: take $a$ as the provisional maximum, then let $b$, then $c$, take its place whenever it is larger.
a,b,c=3,7,5# the 3 numbers to compareifa>=banda>=c:# a is at least as large as the 2 othersm=aelifb>=c:# otherwise b, if it beats cm=belse:# otherwise cm=cprint(f"the maximum of {a}, {b}, and {c} is {m}")
Expected output:
the maximum of 3, 7, and 5 is 7
Question 3. The same comparison, wrapped in a function. The 2 tests are now independent, which is the usual way of writing it: the provisional maximum is updated twice, in sequence.
importitertoolsdefmonmax(a,b,c):"""Return the largest of three numbers, without max()."""m=aifb>m:# strictly greater: a tie keeps the earlier valuem=bifc>m:m=creturnmprint(monmax(3,7,5))print(monmax(-1,-5,-3))print(monmax(2,2,1))print(monmax(0.5,-2,0.25))mismatches=[(a,b,c)fora,b,cinitertools.product(range(-5,6),repeat=3)ifmonmax(a,b,c)!=max(a,b,c)]print()print("triples tested:",11**3)print("mismatches: ",len(mismatches))
Expected output:
7
-1
2
0.5
triples tested: 1331
mismatches: 0
The last lines check the function against the built-in max on every triple of integers between $-5$ and $5$: the count of disagreements is $0$.
Caution: the assignment is =, and the comparison inside an if is ==. Writing if a = b: is a syntax error in Python, so the mistake is caught immediately, but if a == b: where an assignment was meant is not.
Exercise 2
Build a square $3\times3$ matrix of integers of your choice, named $A$.
Test the commands trace(A) and sum(diag(A)).
Write a function $t=\mathrm{matrace}(A)$ that computes the trace of a square $3\times3$ matrix, without using the functions trace, sum, or diag.
Recall that the trace of a square matrix $A=(a_{ij})$ is the sum of its diagonal entries,
$$
\operatorname{tr}(A)=\sum_{i=1}^{n}a_{ii}.
$$
Questions 1 and 2.np.trace computes the trace directly, while np.sum(np.diag(A)) extracts the diagonal with np.diag and then sums it: two routes to the same number.
The diagonal entries are $4$, $5$, and $-6$, and $4+5-6=3$.
Question 3. Walk down the diagonal with a single index and accumulate the entries in a variable initialised at $0$.
importnumpyasnpdefmatrace(A):"""Trace of a square matrix, without trace(), sum(), or diag()."""n=len(A)ifany(len(row)!=nforrowinA):raiseValueError("matrace expects a square matrix")t=0foriinrange(n):t+=A[i][i]# A[i][i] on a list of lists, or on an arrayreturntprint(matrace([[1,2,3],[4,5,6],[7,8,9]]))print(matrace(np.array([[4,-1,2],[0,5,3],[7,2,-6]])))print(matrace([[1,2],[3,4]]))print(matrace([[7]]))try:matrace([[1,2,3],[4,5,6]])exceptValueErroraserr:print("not square ->",err)rng=np.random.default_rng(seed=0)forsizein(1,2,3,5,10):M=rng.integers(-9,10,size=(size,size))print(f"{size}x{size}: matrace = {matrace(M):4d} np.trace = {np.trace(M):4d} "f"agree = {matrace(M)==np.trace(M)}")
The function is written for any size $n$ rather than for $3\times3$ alone, and for any container that supports len and indexing: a list of lists as well as a NumPy array. It also refuses a rectangular matrix, where np.trace happily sums $a_{00}$, $a_{11}$, and so on as far as the shape allows.
Careful with np.diag: on a 2D array it extracts the diagonal, but on a 1D array it does the opposite and builds a diagonal matrix. Matlab's diag has the same two behaviours.
The 3 curves share one figure, as a row of 3 panels. The sampling step must be small with respect to the period $2\pi$ of the sines: about 600 points over the interval, so that the curves are drawn as curves and not as polygons.
importnumpyasnpimportmatplotlib.pyplotaspltfig=plt.figure(figsize=(13,4.2))# 1. the Lissajous curvet=np.linspace(-2*np.pi,2*np.pi,601)ax=fig.add_subplot(1,3,1)ax.plot(np.sin(2*t),np.sin(3*t),lw=1.2)ax.set_aspect("equal")# same scale on both axes: a circle stays roundax.set_title(r"$x=\sin(2t)$, $y=\sin(3t)$")ax.set_xlabel("$x(t)$")ax.set_ylabel("$y(t)$")ax.grid(alpha=0.3)# 2. the same, with a linear driftt=np.linspace(-4*np.pi,4*np.pi,1201)ax=fig.add_subplot(1,3,2)ax.plot(t+np.sin(2*t),t+np.sin(3*t),lw=1.2)ax.set_aspect("equal")ax.set_title(r"$x=t+\sin(2t)$, $y=t+\sin(3t)$")ax.set_xlabel("$x(t)$")ax.set_ylabel("$y(t)$")ax.grid(alpha=0.3)# 3. a curve in spacet=np.linspace(-2*np.pi,2*np.pi,601)ax=fig.add_subplot(1,3,3,projection="3d")ax.plot(t*np.cos(t),t*np.sin(t),t,lw=1.2)ax.set_title(r"$x=t\cos t$, $y=t\sin t$, $z=t$")ax.set_xlabel("$x$")ax.set_ylabel("$y$")ax.set_zlabel("$z$")fig.tight_layout()plt.show()
Left: the Lissajous curve of question 1. Middle: the curve of question 2, a diagonal drift decorated with loops. Right: the spatial curve of question 3, a corkscrew whose radius grows with $t$.
Notice the periods: $x$ has period $\pi$ and $y$ has period $2\pi/3$, so their common period is $2\pi$, and the interval $-2\pi\le t\le2\pi$ describes the closed curve twice. Without set_aspect("equal") the figure is stretched by the shape of the axes, and a closed symmetric curve looks distorted.
The third curve needs projection="3d" in add_subplot: its radius $\sqrt{x^{2}+y^{2}}=|t|$ grows with $|t|$, which draws a corkscrew opening outwards.
Problem: the golden ratio and the Fibonacci sequence
The golden ratio is a proportion originally defined in geometry as the ratio of 2 lengths $a$ and $b$, noted $\varphi$, such that
$$
\varphi=\frac{a}{b}=\frac{a+b}{a}
$$
with $a>b>0$. It appears in painting, sculpture, and architecture, and in nature.
1. The equation satisfied by the golden ratio
Show that $\varphi$ satisfies
$$
\varphi^{2}-\varphi-1=0.
$$
Start from the 2nd form of the ratio and split the fraction:
Python has no real square root of a negative number, but cmath.sqrt returns a complex one, so a single code path covers $\Delta>0$, $\Delta=0$, and $\Delta<0$.
importcmathdefdegre2(a,b,c):"""Return the two roots of a*x**2 + b*x + c = 0."""ifa==0:raiseValueError("a is zero: this is not a second-degree equation")delta=b*b-4*a*c# the discriminantroot=cmath.sqrt(delta)# complex square root: covers delta < 0 as wellreturn(-b+root)/(2*a),(-b-root)/(2*a)fora,b,cin[(1,-1,-1),(1,-3,2),(1,0,1),(2,4,2)]:print(f"a={a}, b={b}, c={c} -> {degre2(a,b,c)}")
Because cmath.sqrt always returns a complex number, so do the roots, even when they are real: they carry a zero imaginary part. To stay in the reals, branch on the sign of $\Delta$ and use math.sqrt when $\Delta\ge0$:
importmathdefdegre2_reel(a,b,c):"""Return the two roots, as floats when the discriminant is positive."""ifa==0:raiseValueError("a is zero: this is not a second-degree equation")delta=b*b-4*a*cifdelta<0:returnNone# no real rootd=math.sqrt(delta)return(-b+d)/(2*a),(-b-d)/(2*a)print(degre2_reel(1,-1,-1))# the golden ratio and its conjugateprint(degre2_reel(1,-3,2))print(degre2_reel(1,0,1))# None: no real root
Since $a>b>0$, $\varphi=\dfrac{a}{b}>1$, which selects the positive root:
$$
\varphi=\frac{1+\sqrt{5}}{2}\approx1.618
$$
The other root is $-\dfrac{1}{\varphi}$, the conjugate golden ratio, whose product with $\varphi$ is $-1$, as Vieta's relation $x_1x_2=\dfrac{c}{a}=-1$ requires.
Sympy confirms the value exactly, and confirms that it cancels the polynomial of question 1:
importsympyasspx=sp.symbols("x")roots=sp.solve(x**2-x-1,x)# x**2 - x - 1 = 0print("roots:",roots)phi_exact=(1+sp.sqrt(5))/2print("positive root:",roots[1])print("difference from (1 + sqrt(5))/2:",sp.simplify(roots[1]-phi_exact))print("phi^2 - phi - 1 =",sp.simplify(phi_exact**2-phi_exact-1))print("phi =",sp.N(phi_exact,20))
Python integers have no fixed width, so the loop does not overflow the way a Matlab double would: it can run to $N=1000$ and beyond. The terms only lose their exactness when they are converted to a float, which happens for $F_n$ at $n=1477$, the 1st term above $1.8\cdot10^{308}$.
5. Numerical convergence of the ratios
Verify numerically that the ratio $\dfrac{F_{n+1}}{F_n}$ tends to the golden ratio.
Print the ratio, its distance to $\varphi$, and that distance multiplied by $\varphi^{2n}$:
The ratio does converge, and the last column is the interesting one: it settles at $2.236068$, which is $\sqrt{5}$, to 6 digits. The distance to $\varphi$ therefore behaves as
Since $\psi<0$, the ratio alternates above and below $\varphi$, as the 2nd column of the output shows; and since $|\psi|^{n}=\varphi^{-n}$ while $F_n\approx\varphi^{n}/\sqrt{5}$, the distance falls like $\varphi^{-2n}$, that is, by a factor $\varphi^{2}\approx2.618$ at each step.
Left: the ratio $F_{n+1}/F_n$ against $\varphi$. Right: the absolute error $|F_{n+1}/F_n-\varphi|$ on a logarithmic scale, along the line $\sqrt{5}\,\varphi^{-2n}$. The convergence is geometric, with ratio $\varphi^{2}$. Illustration, not an output of the script above.
Plot the golden spiral, choosing an arbitrary value for $A$.
$A$ is only a scale: it does not change the shape of the spiral, and $A=1$ is the simplest choice. The constant $B$ is set so that a quarter turn multiplies the radius by $\varphi$,
importnumpyasnpimportmatplotlib.pyplotaspltphi=(1+np.sqrt(5))/2B=np.log(phi)/(np.pi/2)# quarter turn = one factor phiA=1.0# arbitrary scaletheta=np.linspace(0,4*np.pi,800)r=A*np.exp(B*theta)plt.figure(figsize=(6,5.6))plt.plot(r*np.cos(theta),r*np.sin(theta),lw=1.6,color="darkgoldenrod")plt.plot([0],[0],"k+",ms=12)# the poleforkinrange(8):# one mark at each quarter turnturn=k*np.pi/2plt.plot(A*np.exp(B*turn)*np.cos(turn),A*np.exp(B*turn)*np.sin(turn),"o",ms=3,color="black")plt.gca().set_aspect("equal")# without this the spiral is not a spiralplt.xlabel("$x$")plt.ylabel("$y$")plt.title(r"Golden spiral, $r(\theta)=Ae^{B\theta}$")plt.grid(alpha=0.3)plt.show()print("one quarter turn multiplies r by",np.exp(B*np.pi/2))print("two whole turns multiply r by ",np.exp(B*4*np.pi))print("phi**8 = ",phi**8)
Expected output:
one quarter turn multiplies r by 1.618033988749895
two whole turns multiply r by 46.97871376374778
phi**8 = 46.978713763747805
The golden spiral for $A=1$ and $0\le\theta\le4\pi$: 2 turns, during which the radius is multiplied by $\varphi^{8}\approx46.98$. The marks sit at each quarter turn.
During 2 turns the radius grows by a factor $\varphi^{8}\approx47$, so the outer coil is far wider than the inner one and the 2 cannot both be seen in detail on the same figure. set_aspect("equal") keeps the circles centred on the origin circular: without it, the spiral looks elliptical.