Notes Matlab
Notes Matlab
Why MATLAB?
Real-life Applications:
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems.
Example:
MATLAB Interface
The MATLAB interface consists of various components like the Command Window,
Workspace, Command History, and Editor.
Command Window:
Editor:
Workspace:
Command History:
Example Code:
matlab
Copy code
% Creating a matrix
A = [1 2 3; 4 5 6; 7 8 9];
% Accessing elements
element = A(2, 3); % Element at 2nd row, 3rd column
Real-life Applications:
Example Code:
matlab
Copy code
% Saving variables
save('data.mat', 'A');
% Loading variables
load('data.mat');
Includes basic programming constructs such as variables, arrays, functions, and control flow.
Data Types
MATLAB supports various data types such as double, char, logical, cell, and structure arrays.
Example Code:
matlab
Copy code
% Different data types
a = 10; % Double
b = 'hello'; % Character array (string)
c = true; % Logical
d = {1, 2, 3}; % Cell array
e = struct('field1', 1, 'field2', 'value'); % Structure
Creating Variables
Example Code:
matlab
Copy code
% Creating variables
x = 5;
y = [1 2 3 4 5];
Example Code:
matlab
Copy code
% Scalar
a = 5;
% Vector
b = [1 2 3];
% Matrix
c = [1 2; 3 4];
% Operations
result = a + b; % Scalar addition to a vector
result = b * c; % Vector-matrix multiplication
Real-life Applications:
Data can be imported from and exported to various formats such as text files, spreadsheets,
and binary files.
Example Code:
matlab
Copy code
% Importing data
data = readmatrix('data.csv');
% Exporting data
writematrix(data, 'output.csv');
File Editing and Debugging in MATLAB
Scripts are files containing a sequence of MATLAB commands. They operate on data in the
workspace.
matlab
Copy code
% Script file example
x = 1:10;
y = x.^2;
plot(x, y);
Functions are files that take input arguments and return output arguments. They have their
own workspace.
matlab
Copy code
function result = myFunction(a, b)
result = a + b;
end
Breakpoints are used to pause the execution of a script or function to examine the workspace.
Example Code:
matlab
Copy code
% Insert a breakpoint
dbstop in script.m at 2
Error Correction
MATLAB provides various ways to handle and correct errors, including try-catch blocks.
Example Code:
matlab
Copy code
try
% Code that might cause an error
result = myFunction(a, b);
catch ME
% Handle the error
disp(ME.message);
end
MATLAB Graphics I
MATLAB can generate various types of plots such as line, bar, and scatter plots.
Example Code:
matlab
Copy code
% Line plot
x = 1:10;
y = x.^2;
plot(x, y);
% Bar plot
bar(x, y);
% Scatter plot
scatter(x, y);
Plotting Functions
Functions like plot, bar, and scatter are used for plotting data.
Example Code:
matlab
Copy code
% Plotting a sine wave
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
Example Code:
matlab
Copy code
% 2D plot
plot(x, y);
title('Sine Wave');
xlabel('x-axis');
ylabel('y-axis');
% 3D plot
z = cos(x);
plot3(x, y, z);
title('3D Plot');
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
MATLAB Programming I
Conditional Statements
if, else, and elseif statements are used for conditional execution of code.
Example Code:
matlab
Copy code
x = 10;
if x > 0
disp('x is positive');
elseif x < 0
disp('x is negative');
else
disp('x is zero');
end
Iterative Statements
Loops like for and while are used for repetitive tasks.
Example Code:
matlab
Copy code
% For loop
for i = 1:10
disp(i);
end
% While loop
i = 1;
while i <= 10
disp(i);
i = i + 1;
end
Flow Control
MATLAB supports flow control using break, continue, and return statements.
Example Code:
matlab
Copy code
for i = 1:10
if i == 5
continue; % Skip the rest of the code in the loop
end
disp(i);
end
Efficient coding practices include preallocating arrays and avoiding loops when possible.
Example Code:
matlab
Copy code
% Preallocating arrays
n = 1000;
A = zeros(n, 1);
% Avoiding loops
A = rand(1, n);
B = A + 1; % Vectorized operation
Linear Algebra
Example Code:
matlab
Copy code
% Matrix multiplication
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A * B;
Real-life Applications:
Polynomials
MATLAB can handle polynomial operations such as finding roots and evaluating
polynomials.
Example Code:
matlab
Copy code
% Define a polynomial
p = [1 -3 2]; % Represents x^2 - 3x + 2
% Find roots
r = roots(p);
% Evaluate polynomial
x = 1:10;
y = polyval(p, x);
Curve Fitting
Example Code:
matlab
Copy code
% Data
x = 1:10;
y = [2.1, 2.5, 3.6, 4.5, 5.9, 7.2, 8.5, 9.1, 10.2, 11.3];
% Fit a polynomial
p = polyfit(x, y, 2);
Real-life Applications:
Example Code:
matlab
Copy code
% Differentiation
syms x;
f = x^2 + 3*x + 2;
df = diff(f);
% Integration
int_f = int(f);
% Numerical integration
y = sin(x);
integral_value = integral(@(x) sin(x), 0, pi);
Real-life Applications:
GUI Tools:
Example Code:
matlab
Copy code
% Simple GUI using App Designer
app = uifigure;
btn = uibutton(app, 'push', 'ButtonPushedFcn', @(btn,event) disp('Button
pushed!'));
MATLAB Programming II
Example Code:
matlab
Copy code
% Mean and standard deviation
data = [1, 2, 3, 4, 5];
mean_value = mean(data);
std_value = std(data);
% Probability distributions
pd = makedist('Normal');
random_numbers = random(pd, 1, 1000);
Real-life Applications:
Example Code:
matlab
Copy code
% Cell array
c = {1, 'text', [3, 4, 5]};
% Structure array
s = struct('field1', 1, 'field2', 'text');
Performance Measures
Example Code:
matlab
Copy code
% Measure execution time
tic;
pause(1);
elapsedTime = toc;
Example Code:
matlab
Copy code
% Symbolic variables
syms x y;
f = x^2 + y^2;
MATLAB Toolboxes
Example Code:
matlab
Copy code
% Acquire data from a device
ai = analoginput('nidaq', 'Dev1');
addchannel(ai, 0);
start(ai);
data = getdata(ai);
Example Code:
matlab
Copy code
% Signal analysis
t = 0:0.001:1;
x = sin(2*pi*50*t) + sin(2*pi*120*t);
y = fft(x);
Used for acquiring images from cameras and other imaging devices.
Example Code:
matlab
Copy code
% Acquire image
vid = videoinput('winvideo', 1);
start(vid);
img = getsnapshot(vid);
imshow(img);
Example Code:
matlab
Copy code
% Read and display an image
img = imread('peppers.png');
imshow(img);
% Image enhancement
img_enhanced = imadjust(img);
imshow(img_enhanced);
Introduction to SIMULINK
What is SIMULINK?
Example:
SIMULINK Interface
The interface includes the Library Browser, where you can find blocks to build models, and
the Model window, where you assemble your system.
Libraries & Tools
SIMULINK provides a wide range of libraries for different types of systems and applications.
Example Code:
matlab
Copy code
% Create a new model
new_system('myModel');
% Add a block
add_block('simulink/Commonly Used Blocks/Sine Wave', 'myModel/SineWave');
Conclusion
MATLAB is a versatile and powerful tool used across various industries for numerical
computation, data analysis, and simulation. Mastery of MATLAB can significantly enhance
your ability to solve complex problems and create sophisticated models and simulations.