BudiBadu Logo
Samplebadu

MATLAB by Example: Scripts

R2023b

Scripts are files containing MATLAB code. This example shows how to structure a script with sections and comments.

Code

% myscript.m
% This is a comment.

%% Section 1: Initialization
% Double percent sign starts a code section
clear;  % Clear workspace variables
clc;    % Clear command window
close all; % Close all figures

param = 10;

%% Section 2: Calculation
% You can run sections independently (Ctrl+Enter)
result = param ^ 2;

%% Section 3: Output
fprintf('Result is %d\n', result);

Explanation

MATLAB code is saved in files with a .m extension. There are two types of M-files: scripts and functions. A script is simply a sequence of commands that operates on the data in the global workspace. It doesn't accept inputs or return outputs directly, but it can access and modify any variables currently in memory.

A powerful feature of the MATLAB Editor is "Code Sections". By starting a line with two percent signs %%, you define a new section. This divides your script into logical blocks. You can run just the current section by pressing Ctrl+Enter. This is incredibly useful for iterative development and debugging, allowing you to tweak one part of a long script without re-running everything.

Standard practice for scripts often involves a "cleanup" phase at the top. Commands like clear (remove all variables), clc (clear the console), and close all (close plot windows) ensure you are starting from a clean slate, preventing old data from interfering with your current run.

Code Breakdown

4
%% Section 1 creates a visual break and a runnable block in the editor.
6
clear; is crucial for reproducibility, ensuring no hidden state persists.