Difficulty: Beginner | Prerequisites: Read the companion notes on MATLAB Fundamentals (environment, arithmetic, operator precedence) first.
Once you can use the Command Window as a calculator, the next step is saving your work in reusable script files and learning how MATLAB handles variables, output formatting, and its library of built-in mathematical functions. This set of notes covers those topics. Together with the fundamentals notes, it gives you everything from Lecture 13 that you need for labs and exams.
MATLAB scripts (M-files) let you save and rerun sequences of commands. Variables are created by assignment, are case-sensitive, and require no type declaration. Use fprintf for formatted output, and lean on MATLAB's extensive library of built-in math functions (sin, cos, exp, sqrt, log, and many others) rather than writing your own.
Script (M-file)
A plain-text file with the extension .m that contains a sequence of MATLAB statements or function calls. Run it by typing its name (without .m) in the Command Window, or by pressing Run in the editor.
Think of it as a saved recipe: instead of typing each command by hand, you write them once and replay the whole sequence.
MATLAB editor
The built-in text editor for writing and debugging M-files. Open it from the toolbar or by typing edit filename.m at the prompt.
Comment (%)
Text after a % symbol on any line is ignored by MATLAB. Used to explain what your code does. Block comments use %{ ... %}.
In simple terms, comments are notes to your future self (or your grader).
Variable assignment
The statement variableName = expression; creates a variable and stores the result. No type declaration is needed. MATLAB figures out the type from the value.
Case sensitivity
Variable names in MATLAB are case-sensitive. myVar, MyVar, and MYVAR are three different variables.
Semicolon (;) suppression
Appending a semicolon to the end of a statement prevents MATLAB from displaying the result in the Command Window. The computation still happens.
fprintf
A formatted-output function that works like C's printf. Uses format specifiers (%d, %f, %e, %s, %c) and escape characters (\n for newline) to control how values appear.
disp
A simpler output function that displays the value of a variable or a string without format control.
Built-in mathematical functions
MATLAB's standard library of math functions including trigonometric (sin, cos, tan, acos, asin, atan), exponential and logarithmic (exp, log, log10, sqrt), rounding (ceil, floor, round), and utility (abs, sign, max, min). These should only appear on the right-hand side of an assignment.
A script is a text file (.m extension) containing a sequence of MATLAB statements. Often called an M-file.
Create one from the command line: >> edit helloWorld.m
Or click "New Script" in the toolbar to open the editor.
Run a script by typing its filename (without the .m) in the Command Window, or by clicking Run in the editor.
Scripts execute every line in order, top to bottom.
Single-line comment: anything after % on a line is ignored.
Block comment: wrap multiple lines in %{ and %}.
Comment thoroughly. Readable code earns marks and saves you time when debugging.
Variables are created by assignment: x = 5;
No type declaration needed. MATLAB infers the type from the assigned value.
Naming rules:
Case-sensitive (x and X are different variables).
Must start with a letter.
After the first character, any combination of letters, numbers, and underscores (_) is allowed.
A semicolon at the end suppresses the display of the result. Without a semicolon, MATLAB echoes the value.
Built-in variable names to avoid overwriting: ans, eps, i, j, Inf, -Inf, pi, NaN.
Use ii and jj for loop indices instead of i and j.
Numbers default to 64-bit double: x = 5;
Characters use single quotes: char = 'd'; (16-bit char)
Character arrays (strings) use single quotes: myString = 'hello world';
fprintffprintf works like C's printf. It takes a format string followed by the values to insert.
%d integer
%f fixed-point decimal (e.g. %4.2f for 4 characters wide, 2 decimal places)
%e scientific notation
%s string
%c single character
\n newline
Example:
x = 6;
y = 46.50;
fprintf(' x = %d \n', x); % Output: x = 6
fprintf(' y = %4.2f \n', y); % Output: y = 46.50Use help disp or doc disp to look up the simpler disp function.
Trigonometric:
cos(x) Cosine
sin(x) Sine
tan(x) Tangent
acos(x) Arc cosine
asin(x) Arc sine
atan(x) Arc tangent
Exponential and logarithmic:
exp(x) Exponential (e^x)
sqrt(x) Square root
log(x) Natural logarithm (ln)
log10(x) Common logarithm (base 10)
Rounding:
ceil(x) Round towards positive infinity
floor(x) Round towards negative infinity
round(x) Round to nearest integer
Utility:
abs(x) Absolute value
sign(x) Signum function (returns -1, 0, or 1)
max(x) Maximum value
min(x) Minimum value
Critical rule: only use built-in functions on the right-hand side of an expression. Never reassign a built-in function name (e.g. never write sin = 5;), or you will break that function for the rest of your session.
fprintf format specifier syntax:
fprintf('format string', value1, value2, ...)Common specifiers:
%d integer
%f fixed-point (default 6 decimals)
%4.2f 4 characters wide, 2 decimal places
%e scientific notation
%s string
%c character
\n newlineVariable assignment syntax:
variableName = value;
variableName = expression;Block comment syntax:
%{
This entire block is a comment.
MATLAB ignores all of it.
%}The fprintf function is how you produce readable, formatted reports from your MATLAB analyses, whether that is a lab report, a data summary, or debug output during development. The built-in math functions (sin, cos, exp, log, etc.) are the building blocks of every engineering calculation you will run in MATLAB, from circuit analysis to structural mechanics to signal processing.
Students often reassign built-in function names as variables (e.g. sin = 3;) and then wonder why sin(pi/2) throws an error. Once you overwrite a built-in name, it stays broken until you clear that variable.
Students assume log(x) in MATLAB is the base-10 logarithm because that is what "log" means on most calculators. In MATLAB, log(x) is the natural logarithm (ln). For base 10, use log10(x).
Students mix up single quotes and double quotes when creating strings. In older versions of MATLAB, character arrays use single quotes ('hello'). Double quotes create a different type (string object). This lecture uses single quotes.
Students forget the \n in fprintf and end up with all output jammed onto one line.
Expect questions that show a block of code and ask what appears in the Command Window. Track which lines have semicolons (suppressed) and which do not (displayed).
Know your fprintf format specifiers cold. A question might give you a fprintf call and ask for the exact output string.
Be able to identify valid and invalid variable names (must start with a letter, case-sensitive, no reserved words).
Know what log(x) means in MATLAB (natural log, not base 10) and how to get the base-10 version (log10).
Understand why overwriting a built-in function name is dangerous and how to fix it (clear variableName).
True or false: You must declare the type of a variable before using it in MATLAB. (False.)
What does % do in a MATLAB script? (Marks the rest of the line as a comment.)
Fill in the blank: log(x) in MATLAB computes the ________ logarithm. (Natural / ln.)
True or false: fprintf(' x = %d \n', 5); prints x = 5 followed by a newline. (True.)
What happens if you type cos = 2; and then try to compute cos(pi)? (Error. You have overwritten the built-in function.)
Q: Given the following code, what is printed to the Command Window?
x = 5;
x = x + 1;
y = 1.3*45 - 2*x;
fprintf(' y = %4.2f \n', y);A: y = 46.50. After x = x + 1, x is 6. Then y = 1.3*45 - 2*6 = 58.5 - 12 = 46.5. The format %4.2f displays it as 46.50.
Q: Which of these are valid MATLAB variable names: myVar, 2ndValue, _temp, data_set, for?
A: myVar and data_set are valid. 2ndValue is invalid (starts with a digit). _temp is invalid (must start with a letter). for is a reserved keyword and should not be used.
Q: What is the output of fprintf(' %s \n', 'hello world');?
A: hello world followed by a newline. The %s specifier inserts the string.
Q: How do you calculate sin(90 degrees) in MATLAB?
A: result = sin(pi/2);. MATLAB's trigonometric functions use radians, not degrees. 90 degrees equals pi/2 radians. (Alternatively, use sind(90) if your version supports it.)
Q: You accidentally typed sqrt = 16;. How do you fix it so that sqrt works as a function again?
A: Type clear sqrt to remove the variable. After that, MATLAB will once again treat sqrt as the built-in square-root function.
Scripts are the gateway to MATLAB functions (covered in later lectures), where you define your own reusable blocks of code with inputs and outputs. The fprintf formatting skills transfer directly to file I/O when you start reading from and writing to data files. The built-in math functions here are the same ones you will use inside loops, conditionals, and vectorised operations throughout the rest of the course.
MATLAB script, M-file, MATLAB editor, MATLAB comments, block comment, variable assignment MATLAB, case-sensitive variables, fprintf, format specifiers, %d %f %e %s %c, disp, MATLAB built-in functions, sin cos tan MATLAB, exp sqrt log log10, ceil floor round, abs sign max min, COE 301 Lecture 13, MATLAB variables, semicolon suppression, character array, MATLAB string