ENGGEN 131 Chap.3 MATLAB Arrays and Loops
MATLAB Arrays and Loops
This chapter treats an array as values plus shape and legal positions. It covers one-based indexing, colon sequences, linspace, row and column orientation, matrix versus elementwise operators, for and while loops, trace tables and loop invariants. Worked reductions and neighbour comparisons show why dimensions and stopping conditions are part of every correct answer.
What this chapter covers
- 01
Row vectors, column vectors and dimensions
- 02
Colon sequences and evenly spaced points
- 03
Scalar, range and logical indexing
- 04
Matrix and elementwise arithmetic
- 05
For loops, while loops and invariants
Worked example · free
Accumulate signed updates
- 1The first two totals are 4 and 3.
- 1The next three totals are 10, 8 and 17.
- 1The final subtraction produces 14.
Key terms
- Array shape
- The ordered dimensions of an array, including row or column orientation.
- Elementwise operator
- An operator that acts independently on corresponding array elements.
- Loop invariant
- A statement that remains true after each completed iteration.
MATLAB Arrays and Loops FAQ
Why does MATLAB indexing begin at one?
MATLAB defines the first array position as one, so index calculations and loop bounds must follow that convention consistently. Rehearse this distinction with a fresh index and loop-state trace before relying on program output.
When do I need a dotted operator?
Use a dotted operator when the engineering relationship applies independently to corresponding elements rather than following matrix algebra. Test the claim on a boundary case where the index and loop-state assumptions become visible.
How do I stop an adjacent-pair loop safely?
For a vector of length n, compare positions i and i+1 only while i runs from one through n minus one. Write the expected index and loop-state state first, then compare it carefully with execution.
Exam move
Begin with shape. Beside every array, write its number of rows and columns, and beside every index expression, write the positions it generates. Expand short colon sequences before selecting values. Distinguish start-step-stop notation, whose endpoint appears only when reached by repeated steps, from linspace, which specifies a number of points including both endpoints.
Read nested expressions inside out: create the index, perform the selection, then apply arithmetic. This order exposes illegal positions and unexpected orientation early. For every loop, predict the execution count before tracing its body. Create a table with the control value, state before the update, expression evaluated, state after the update and any output element written. Never replace several rows with the word repeat.
For a while loop, include the initial condition check so a zero-iteration case remains visible. For a for loop, expand the control sequence first. Mark the first legal index, last legal index and first value that should not execute. State a loop invariant in one sentence. For accumulation, say that the running total equals the sum of the processed prefix.
For a search, say what has been established about positions already inspected. For array construction, say which output positions have valid values after each pass. Check that the invariant is true before the first iteration, preserved by one iteration and strong enough to give the required answer at termination. This turns a trace into an explanation of correctness rather than a list of numbers.
Use a boundary suite containing an empty array if the contract permits it, one element, the shortest input that activates neighbour logic, and a mixed normal case. For adjacent-pair logic, show why the control range stops one position before the final array index. For accumulation, include positive and negative values so an accidental absolute value or biased initial value becomes visible.
Check both result values and shape, because a transposed answer can contain all the right numbers while breaking a later calculation. Compare loop and vectorised forms through explicit proof obligations. Write the domain visited by the loop and the size and true positions of the logical mask.
Check that both read the same version of the input, select the same elements, apply the same update and preserve the same output orientation. Be cautious with in-place neighbour updates: a later loop iteration may read an earlier changed value, while a vector expression often reads the original array simultaneously. Construct a small counterexample whenever update order might matter.
Finish by tracing one for loop, one while loop and one logical-indexing solution without MATLAB. State termination, invariant and final shape for each. Then run the code and compare the exact trace. Record off-by-one mistakes in terms of the intended legal domain rather than memorising a corrected header. A robust solution can explain why the start and stop values follow from the requirement.
Fluency means moving among expanded indices, trace tables, invariants and vector expressions while preserving the same computational meaning. Conclude with a reconstruction task that starts from a short mixed vector and asks for the same transformation in a loop and with logical indexing. Expand every generated index, predict execution count and maintain a before-and-after state row for each pass.
Write the invariant that connects the processed prefix to the partial result. Then build the logical mask, list its true positions and prove that both forms select the same elements, read the same input state and preserve the same orientation. Add a one-element case and a neighbour-dependent case to test boundaries and update order.
If the methods diverge, produce the smallest counterexample instead of assuming vectorisation is preferable. This integrated task checks index domains, shapes, termination, invariants and semantic equivalence without relying on MATLAB to supply the reasoning.