3. Scripts, Functions, and Control Flow
As your projects grow, you'll move beyond the Command Window to write more organized and reusable code using scripts and functions, controlled by essential programming constructs.
3.1. Writing and Running Scripts (.m files)
A script is a series of MATLAB commands stored in a .m file. It runs commands sequentially as if you typed them in the Command Window, sharing the same Workspace.
% my_script.m
disp('Starting script...');
x = 1:5;
y = x.^2;
plot(x, y);
title('My First Plot from Script');
disp('Script finished.');
To run, simply type my_script in the Command Window (ensure it's in the Current Folder or MATLAB path).
3.2. Defining and Calling Functions
Functions are reusable blocks of code that operate in their own local Workspace, accepting inputs and returning outputs. Save each function in its own .m file with the same name as the function.
% my_function.m
function [sum_val, prod_val] = my_function(a, b)
% This function calculates the sum and product of two numbers.
sum_val = a + b;
prod_val = a * b;
end
Call it from the Command Window or another script/function:
>> [s, p] = my_function(5, 10);
>> disp(['Sum: ', num2str(s), ', Product: ', num2str(p)]);
Sum: 15, Product: 50
3.3. Control Flow Statements
Control the execution flow of your code:
if-else-end: Conditional execution.if x > 10 disp('x is greater than 10'); elseif x == 10 disp('x is 10'); else disp('x is less than 10'); endforloops: Iterate a fixed number of times.for i = 1:5 disp(['Iteration: ', num2str(i)]); endwhileloops: Iterate as long as a condition is true.count = 1; while count <= 3 disp(['Count: ', num2str(count)]); count = count + 1; end
Key Concept: Functions promote modularity and reusability, while control flow structures enable dynamic program behavior.