ENGGEN 131 Chap.1 MATLAB Scripts and Functions
MATLAB Scripts and Functions
This chapter separates MATLAB console work, scripts and functions by the state each can see. It develops explicit input-output contracts, local function workspaces, return values, scalar expansion and trace tables. Original examples show how to predict a call before running it, test a conversion function at meaningful points and detect a hidden dependence on a base-workspace variable.
What this chapter covers
- 01
Base workspace and local function workspace
- 02
Scripts for orchestration and functions for reusable transformations
- 03
Function headers, input order and returned outputs
- 04
Right-to-left evaluation of assignments
- 05
Contract tests using simple and boundary inputs
Worked example · free
Shift a sensor vector and return its peak
- 1x(1) is 2 because MATLAB indices begin at one.
- 1Scalar expansion gives y=[0 3 2 7 5 10].
- 1The maximum returned value is 10.
Key terms
- Base workspace
- The MATLAB workspace used by the command window and scripts.
- Function workspace
- The local set of names created for one function call.
- Scalar expansion
- Applying a scalar operation across compatible array elements.
MATLAB Scripts and Functions FAQ
When should I write a function instead of a script?
Use a function when a calculation should have explicit inputs and outputs, be reusable or be tested independently without relying on unrelated base-workspace names. This boundary makes isolated tests dependable.
Why did a local variable disappear after the call?
A function workspace ends when the call returns. Only values named as outputs are passed back to the caller; helper names remain local. Test the claim on a boundary case where the workspace and function-contract assumptions become visible.
How do I test a small MATLAB function?
Choose an input whose answer is obvious, a boundary value and another case that distinguishes the intended formula from a tempting but incorrect grouping. Write the expected workspace and function-contract state first, then compare it carefully with execution.
Exam move
Begin each revision session by separating three execution settings: commands typed at the console, lines run by a script, and statements executed inside a function. Make a two-column inventory of names visible in the base workspace and names created locally by a function call. This is not clerical work: it prevents a trace from borrowing a value that the function was never given.
For every example, write the function header as a contract containing the input order, expected shapes, output order and intended meaning. Trace assignments from right to left. Record the values read, the operator precedence applied, the intermediate result and the destination that receives it.
Mark whether the line is suppressed with a semicolon, but keep display separate from computation: a suppressed value still exists, while an unsuppressed local value can disappear when the call returns. When a function invokes another function, start a new local-state column rather than merging both calls. On return, copy back only declared outputs and cross out temporary names whose lifetimes have ended.
Use a three-part test set. First choose a simple input whose result can be calculated mentally. Second choose a boundary such as zero, one element or an exact threshold. Third choose an input whose shape or sign distinguishes the intended calculation from a tempting alternative. If vector input is permitted, test a row and a column separately when orientation matters.
Predict values and dimensions before execution, then compare at the earliest line where the program differs. The first mismatch is better diagnostic evidence than the final wrong answer. Practise turning a script into a function. Identify which base-workspace names are genuine inputs, which produced values should become outputs and which intermediate names should remain local.
Then perform the reverse exercise: write a short script that prepares inputs, calls the function and handles its returned values without depending on hidden leftovers from earlier commands. Explain why reproducibility improves when the transformation has an explicit interface. Also check that input and output positions match at the call site; familiar variable names do not override positional matching.
For exam traces, annotate every name with caller or local scope and every value with scalar, row, column or matrix shape. If the question asks what is printed, list only unsuppressed expressions in execution order. If it asks what survives after return, list caller variables and captured outputs, not local helpers.
If an error occurs, state whether it comes from invalid syntax, a mismatched call contract, an unavailable name or incompatible dimensions. This vocabulary makes the explanation specific and keeps the correction tied to evidence. Finish with a closed-book reconstruction. Write a small conversion function with two outputs, trace it on one scalar and one vector, and design tests for wrong grouping and hidden state.
Check the result by running only after the paper prediction is complete. Record any discrepancy in an error log using four headings: expectation, observation, first differing line and repaired contract. Revisit that log rather than repeating comfortable exercises. Mastery means being able to predict state movement and justify the interface, not merely producing code that works once in a prepared workspace.
As a final check, take unfamiliar code and create a scope-and-shape ledger before reading its output. Identify every base name, parameter, local variable and return value; then annotate each with its current dimensions. Predict which statements display text and which merely update memory. Rewrite one hidden dependency as an explicit input and explain how that change makes the function reproducible.
Finally, design a scalar case, a vector case and a deliberately missing-name case. For each, record the expected result or error before running. If the program disagrees, stop at the first differing assignment and revise the contract rather than patching a later symptom.
This last audit combines workspace boundaries, positional arguments, output capture, shape reasoning and test design in one exercise, so it reveals whether the chapter methods can be applied together under exam conditions.