Learn MATLAB with Real Code Examples
Updated Nov 21, 2025
Code Sample Descriptions
1
MATLAB Counter and Theme Toggle
count = 0;
isDark = false;
function updateUI()
disp(['Counter: ', num2str(count)]);
disp(['Theme: ', ternary(isDark, 'Dark', 'Light')]);
end
function increment()
global count;
count = count + 1;
updateUI();
end
function decrement()
global count;
count = count - 1;
updateUI();
end
function reset()
global count;
count = 0;
updateUI();
end
function toggleTheme()
global isDark;
isDark = ~isDark;
updateUI();
end
% Simulate actions
updateUI();
increment();
increment();
toggleTheme();
decrement();
reset();
Demonstrates a simple counter with theme toggling using MATLAB scripts and console output.
2
MATLAB Random Number Generator
for i = 1:3
num = randi([1, 100]);
disp(['Random ', num2str(i), ': ', num2str(num)]);
end
Generates random numbers between 1 and 100 and displays them.
3
MATLAB Todo List
todos = {};
function addTask(task)
global todos;
todos{end+1} = task;
disp(todos);
end
function removeTask(index)
global todos;
todos(index) = [];
disp(todos);
end
% Simulate actions
addTask('Buy milk');
addTask('Write MATLAB code');
removeTask(1);
Adds and removes tasks from a todo list.
4
MATLAB Dice Roller
for i = 1:3
roll = randi([1,6]);
disp(['Roll ', num2str(i), ': ', num2str(roll)]);
end
Rolls a six-sided dice three times.
5
MATLAB Countdown Timer
count = 5;
while count >= 0
disp(['Countdown: ', num2str(count)]);
count = count - 1;
end
disp('Done!');
Counts down from 5 to 0.
6
MATLAB Prime Checker
nums = [7, 10, 13];
for i = 1:length(nums)
n = nums(i);
if isprime(n)
disp([num2str(n), ' is Prime']);
else
disp([num2str(n), ' is Not Prime']);
end
end
Checks if numbers are prime.
7
MATLAB Temperature Converter
cToF = @(c) c*9/5 + 32;
fToC = @(f) (f-32)*5/9;
disp(['25°C = ', num2str(cToF(25)), '°F']);
disp(['77°F = ', num2str(fToC(77)), '°C']);
Converts Celsius to Fahrenheit and Fahrenheit to Celsius.
8
MATLAB Shopping Cart
cart = {};
prices = [];
def addItem(item, price)
global cart prices;
cart{end+1} = item;
prices(end+1) = price;
disp(cart);
disp(['Total: ', num2str(sum(prices))]);
end
def removeItem(index)
global cart prices;
cart(index) = [];
prices(index) = [];
disp(cart);
disp(['Total: ', num2str(sum(prices))]);
end
% Simulate actions
addItem('Apple', 2);
addItem('Banana', 3);
removeItem(1);
Adds and removes items in a shopping cart with total cost.
9
MATLAB Name Greeting
function greet(name)
disp(['Hello, ', name, '! Welcome!']);
end
% Simulate actions
greet('Saurav');
greet('Alice');
greet('Bob');
Greets users by name.
10
MATLAB Stopwatch
time = 0;
while time < 5
disp(['Stopwatch: ', num2str(time), ' seconds']);
time = time + 1;
end
disp('Done!');
Simulates a stopwatch incrementing seconds.