Basic Tutorial Points
1. Environment
Command Window: Enter commands interactively.
Editor: Write, save, and run scripts (.m files).
Workspace: Variables created during session.
Current Folder: Files location.
Figure Window: For plots and graphics.
2. Basic Commands
clc % Clear command window
clear % Clear all variables from workspace
close all % Close all figures
3. Scripts and Functions
Scripts: files containing sequence of commands (filename.m).
Functions: reusable code blocks with inputs and outputs.
Example function:
function y = squareNum(x)
y = x^2;
end
Call: result = squareNum(5);
4. Clear Specific Variables
a = 1; b = 2; c = 3;
clear b
5. Use input to Get User Input/output
Direct input
A=2
n = input('Enter a numberA= ')
Output
Use disp() or fprintf() for variable checking;
6. Using fprintf for Formatted Output
a = 12.3456;
fprintf('Value with 2 decimals: %.2f\n', a)
7. User Input and Output
Prompt user input
name = input('Enter your name: ', 's'); % 's' for string input
age = input('Enter your age: ');
fprintf('Hello %s, you are %d years old.\n', name, age);
8. Variables and Data Types
x = 5; % Numeric scalar
y = 3.2;
name = ''; % String
A = [1 2 3; 4 5 6]; % Matrix (2x3)
9. Vectors and Matrices
v = 1:5; % Row vector [1 2 3 4 5]
w = 0:0.1:1; % Row vector from 0 to 1 with step 0.1
M = [1 2; 3 4]; % 2x2 matrix
size(M) % Dimensions of M
length(v) % Number of elements in vector v
10. Use unique to Remove Duplicates
A = [1 2 2 3 4 4 5];
B = unique(A);
disp(B)
11. Basic Arithmetic Operations
a = 5; b = 3;
c = a + b; % Addition
d = a - b; % Subtraction
e = a * b; % Multiplication
f = a / b; % Division
g = a^2; % Power
% Element-wise operations on vectors/matrices
v1 = [1 2 3];
v2 = [4 5 6];
v3 = v1 .* v2; % Element-wise multiplication
12. Calculate Absolute Value
A = [-1 -5 3];
absA = abs(A);
disp(absA)
13. Solve Quadratic Equation Using Formula
a = 1; b = -3; c = 2;
D = b^2 - 4*a*c;
x1 = (-b + sqrt(D)) / (2*a);
x2 = (-b - sqrt(D)) / (2*a);
disp([x1 x2])
14. Use linspace to Generate Points
x = linspace(0, 10, 50);
disp(x)
15. Generate a Logarithmic Scale Vector
v = logspace(0, 2, 10); % From 10^0 to 10^2
disp(v)
16. Find Prime Numbers Using isprime
nums = 1:20;
primes = nums(isprime(nums));
disp(primes)
17. Convert Cell Array to Numeric Array
C = {'1', '2', '3'};
nums = str2double(C);
disp(nums)
18. Convert a String to a Number
str = '3.1415';
num = str2double(str);
disp(num);
19. Convert Numeric Array to String Array
nums = [10, 20, 30];
strs = string(nums);
disp(strs)
20. Convert Numeric to Cell Array
nums = [1 2 3];
C = num2cell(nums);
disp(C)
21. Convert Date String to datetime
dt = datetime('2025-06-25', 'InputFormat', 'yyyy-MM-dd');
disp(dt)
22. Convert Between Cell and String Arrays
C = {'apple','banana'};
S = string(C);
disp(S)
C2 = cellstr(S);
disp(C2)
23. Concatenate Strings Horizontally
s1 = 'MATLAB ';
s2 = 'Rocks';
s3 = [s1 s2];
disp(s3)
24. Create a Cell Array of Different Data Types
C = {42, 'hello', [1 2 3]};
disp(C)
25. Convert Table to Cell Array
T = table([1;2],[3;4],'VariableNames',{'A','B'});
C = table2cell(T);
disp(C)
26. Calculate Cumulative Sum
A = 1:5;
cumsumA = cumsum(A);
disp(cumsumA)
27. Element-wise Power Operation
A = [1 2 3];
B = A.^2;
disp(B)
28. Flip Matrix Up-Down
A = [1 2; 3 4];
B = flipud(A);
disp(B)
29. Find the Rank of a Matrix
A = [1 2; 3 4];
r = rank(A);
disp(r)
30. Convert Degrees to Radians and Back
deg = 45;
rad = deg2rad(deg);
deg_back = rad2deg(rad);
fprintf('Degrees: %.2f, Radians: %.4f, Back: %.2f\n', deg, rad, deg_back);
31. Convert Decimal to Binary String
dec = 23;
binStr = dec2bin(dec);
disp(binStr)
32. Calculate Logarithm with Custom Base
x = 100;
base = 10;
val = log(x)/log(base);
disp(val)
33. Extract Real and Imaginary Parts of Complex Number
z = 3 + 4i;
re = real(z);
im = imag(z);
disp([re, im])
34. Matrix Element-wise Operations with .* and ./
A = [1 2; 3 4];
B = [2 0; 1 5];
C = A .* B; % Element-wise multiplication
D = A ./ B; % Element-wise division
disp(C)
disp(D)
35. Convert Numeric Matrix to Table
A = magic(3);
T = array2table(A, 'VariableNames', {'A','B','C'});
disp(T)
36. Convert Numeric Array to Logical
A = [0 1 2 0];
B = logical(A);
disp(B)
37. Use feval to Evaluate Function Handle
f = @sin;
x = pi/2;
y = feval(f,x);
disp(y)
38. Extract Date and Time Components
dt = datetime('now');
disp(year(dt))
disp(month(dt))
disp(day(dt))
disp(hour(dt))
disp(minute(dt))
39. Calculate Vector Magnitude
v = [3 4 5];
mag = norm(v);
disp(mag)
40. Matrix Transpose
A = [1 2; 3 4];
At = A';
disp(At)
41. Extract Diagonal of a Matrix
A = magic(4);
d = diag(A);
disp(d)
42. Create Identity Matrix
I = eye(5);
disp(I)
43. Control Flow
If-Else
if x > 0
disp('Positive')
elseif x == 0
disp('Zero')
else
disp('Negative')
end
For Loop
for i = 1:5
disp(i)
end
While Loop
count = 1;
while count <= 5
disp(count)
count = count + 1;
end
44. Vectorization
x = 0:0.01:1;
y = x.^2 + 3*x + 2; % Vectorized instead of loop
45. Loading and Saving Data
save('mydata.mat', 'x', 'y') % Save variables
load('mydata.mat') % Load variables
46. Useful Built-in Functions
Function Description
zeros(n,m) Create n-by-m matrix of zeros
ones(n,m) Create n-by-m matrix of ones
eye(n) Create n-by-n identity matrix
rand(n,m) Random matrix uniform [0,1]
mean(A) Mean of array
std(A) Standard deviation
sum(A) Sum of array elements
disp(x) Display variable or text
input() User input from keyboard
48. Advanced Array and Matrix Operations
Indexing and slicing
A = [1 2 3; 4 5 6; 7 8 9];
val = A(2,3); % Element in 2nd row, 3rd column (6)
row2 = A(2,:); % Entire 2nd row
col3 = A(:,3); % Entire 3rd column
subA = A(1:2, 2:3); % Submatrix (first 2 rows, columns 2 and 3)
Modifying elements
A(3,1) = 10; % Change element at (3,1) to 10
A(:,2) = [20;30;40]; % Replace 2nd column
Logical indexing
B = A(A > 5); % Returns elements greater than 5
49. File Input/Output
Reading and writing text files
data = load('data.txt'); % Load numeric data
dlmwrite('output.txt', data*2) % Write data multiplied by 2
Reading CSV
T = readtable('data.csv');
head(T)
Writing CSV
writetable(T, 'out.csv')
Eigenvalues and eigenvectors
matlab
CopyEdit
[V, D] = eig(A);
disp(D) % eigenvalues
disp(V) % eigenvectors
50. Function Handles and Passing Functions
Assign a function to a variable
f = @(x) sin(x).^2 + cos(x).^2;
x = 0:0.1:2*pi;
y = f(x);
plot(x,y)
Pass functions as arguments
function result = integrateFunc(f, a, b)
result = integral(f, a, b);
end
int_val = integrateFunc(@(x) x.^2, 0, 1);
disp(int_val)
51. File Operations: Reading/Writing Images
img = imread('peppers.png'); % Read image file
imshow(img)
imwrite(img, 'peppers_copy.png') % Save image file
52. Using for Loop with Step Size
for i = 1:2:10
disp(i)
end
53. Using sort with Descending Order
A = [5 2 8 1];
B = sort(A, 'descend');
disp(B)
54. Calculate Matrix Determinant
A = [1 2; 3 4];
detA = det(A);
disp(detA)
54. Using strcat to Concatenate Strings
s1 = 'Hello';
s2 = 'World';
s3 = strcat(s1, {' '}, s2);
disp(s3)
55. Calculate RMS Value of Signal
x = randn(1,1000);
rmsVal = rms(x);
disp(rmsVal)
56. Calculate Mean and Standard Deviation
data = randn(1,100);
meanVal = mean(data);
stdVal = std(data);
fprintf('Mean=%.3f, Std=%.3f\n', meanVal, stdVal
57. Simple If-Else Statement
x = 5;
if x > 0
disp('Positive')
else
disp('Non-positive')
end
58. Using mod to Check Even/Odd
num = 7;
if mod(num,2) == 0
disp('Even')
else
disp('Odd')
end
59. Convert Degrees to Radians
deg = 180;
rad = deg2rad(deg);
disp(rad)
60. Calculate Dot Product of Two Vectors
a = [1 2 3];
b = [4 5 6];
dp = dot(a,b);
disp(dp)
61. Calculate Cross Product of Two Vectors
a = [1 2 3];
b = [4 5 6];
cp = cross(a,b);
disp(cp)
62. Subfunctions and Nested Functions
Functions inside files for modularity
function main()
a = 5;
b = 10;
disp(add(a,b))
end
function c = add(x,y)
c = x + y;
end
63. Calculate Factorial Using Loop
n = 5;
fact = 1;
for i = 1:n
fact = fact * i;
end
disp(fact)
64. Vectorization Tips
Replace loops with vectorized code for speed
% Loop way
for i = 1:1000
y(i) = sin(i*0.01);
end
% Vectorized way
x = (1:1000)*0.01;
y = sin(x);
65. Error Handling with try-catch
result = 10 / 0;
catch ME
disp('Error occurred:')
disp(ME.message)
end
66. Using MATLAB Apps and Toolboxes
Use built-in apps like Curve Fitting, Signal Analyzer, etc.
Access via Apps tab in MATLAB.
67. Data Import & Export
Import data from Excel:
data = readmatrix('data.xlsx');
Export data to Excel:
writematrix(data, 'output.xlsx');
Import specific sheet or range:
opts = detectImportOptions('data.xlsx','Sheet','Sheet2');
data = readmatrix('data.xlsx', opts);
68. Find the Minimum Value and Its Index
A = [5, 3, 9, 1, 6];
[minVal, idx] = min(A);
fprintf('Minimum value: %d at index %d\n', minVal, idx);
69. Working with Dates and Times
t = datetime('now');
disp(t)
dt = days(5);
t2 = t + dt;
disp(t2)
70. Reading and Plotting Data from CSV
data = readtable('data.csv');
plot(data.Time, data.Temperature)
xlabel('Time')
ylabel('Temperature')
title('Temperature vs Time')
71. Using switch-case Control Structure
x = 'B';
switch x
case 'A'
disp('Grade A')
case 'B'
disp('Grade B')
otherwise
disp('Other Grade')
end
72. Handling Complex Numbers
z = 3 + 4i;
r = abs(z); % Magnitude
theta = angle(z); % Phase (radians)
disp([r, theta])
73. Nested For Loops with Conditional Break
for i=1:5
for j=1:5
if i+j > 6
break
end
fprintf('i=%d, j=%d\n', i, j)
end
end
74. Removing Duplicates from Arrays
A = [1 2 3 2 4 1];
B = unique(A);
disp(B)
75. Using linspace with Variable Steps
x = linspace(0,10,50);
y = sin(x);
plot(x,y)
76. Finding Eigenvalues and Eigenvectors
A = [2 1; 1 2];
[V,D] = eig(A);
disp(D)
disp(V)
77. Using switch-case Control Structure
matlab
CopyEdit
val = 3;
switch val
case 1
disp('One');
case 2
disp('Two');
otherwise
disp('Other');
end
78. Read Data From Excel with readtable
data = readtable('data.xlsx');
disp(data.Properties.VariableNames)
79. Using fprintf to Format Strings
name = 'John';
age = 30;
fprintf('%s is %d years old.\n', name, age)
80. Saving Data to MAT-File
a = 1:10;
save('myData.mat', 'a')