Porting a MATLAB problem-generation algorithm to Python — a first step toward an interactive Python web app for the course platform.
matlab/generate_problem.m |
Original MATLAB function: picks random values for a beam problem (length, load, load position) and computes the reaction force. |
python/generate_problem.py |
Direct Python port — same logic, line for line. |
python3 python/generate_problem.pyBeam length 4.00 m, load 1100.0 N at 3.20 m from support A.
Reaction force at A: 220.00 N
| MATLAB | Python | Why |
|---|---|---|
function ... end |
def ...: |
Python uses indentation instead of end. |
rng(seed); |
rng = random.Random(seed) |
Same idea, seeds the random generator. |
L_values = 3:0.5:8; |
[round(3 + 0.5*i, 2) for i in range(11)] |
MATLAB range syntax has no one-line Python equivalent. |
randi(length(L_values)) (1-based index) |
rng.choice(L_values) |
Python picks the value directly, no index needed. |
problem.L = L; (struct) |
problem = {"L": L} (dict) |
Same purpose, named fields. |
fprintf('%.2f', x) |
f"{x:.2f}" |
Same formatting, Python syntax. |
The engineering — ranges, formula, answer — is unchanged. Only the syntax moved.
The same seed does not give the same problem. rng(seed) seeds MATLAB's
Mersenne Twister and randi draws from it; random.Random(seed) seeds
Python's, and choice consumes it differently. Both are reproducible on their
own platform, and neither reproduces the other.
For a single problem this is invisible — the parameters are drawn from the same sets and the physics is identical, so the output is equally valid. It matters if seeds are ever used as stable identifiers: assigning "problem 47" to a class and expecting MATLAB and Python to produce the same beam would quietly fail.
Two ways to close it, depending on what the platform needs:
- Store the drawn parameters, not the seed. A problem is then
(L, P, a), which is portable across any language and any future generator. - Draw indices from a shared source. Emit the index triple once, and have both implementations look up the same positions in the same value sets.
The first is the more durable choice, since it survives changing the generator at all. Worth deciding before there's a question bank keyed on seeds.
Port the rest of the MATLAB algorithms the same way, then wrap them in a Python web app. Adding a check that runs both implementations across the parameter sets and compares reaction forces would make each port verifiable rather than eyeballed.