MATLAB Basics for Electrical Engineering

MATLAB (Matrix Laboratory) is a high-performance programming language for technical computing. It's widely used in electrical engineering for circuit analysis, signal processing, control systems, and more.

Why MATLAB for Electrical Engineering? MATLAB provides specialized toolboxes for EE applications, including Simulink for system modeling, Signal Processing Toolbox, Control System Toolbox, and Simscape Electrical for circuit simulation.

Getting Started

The MATLAB environment consists of:

  • Command Window: For entering commands and variables
  • Workspace: Shows all defined variables
  • Current Folder: File browser for MATLAB files
  • Editor: For writing and editing scripts and functions
Basic MATLAB Commands
% Basic MATLAB operations
2 + 3 * 5  % Basic arithmetic
(2 + 3) * 5  % Parentheses change order

% Assigning variables
voltage = 120;  % Voltage in volts
current = 2.5;  % Current in amperes
resistance = voltage / current  % Ohm's Law

% Displaying results
fprintf('Resistance: %.2f ohms\n', resistance)

% Complex numbers (important for AC circuit analysis)
Z = 3 + 4i;  % Impedance with real and imaginary parts
magnitude = abs(Z)
phase = angle(Z) * 180/pi  % Convert to degrees

MATLAB Environment

Understanding the MATLAB workspace is essential for efficient programming and analysis.

Useful Commands

clc           % Clear command window
clear         % Clear workspace variables
clear var1 var2  % Clear specific variables
who           % List variables in workspace
whos          % Detailed variable list
help command  % Get help on a command
doc command   % Open documentation
save filename % Save workspace
load filename % Load workspace

Script Files

Scripts are files with .m extension containing MATLAB commands. They're useful for automating repetitive tasks.

% Example script: circuit_analysis.m
% This script calculates power in a circuit

V = 120;  % Voltage
I = 2.5;  % Current
P = V * I;  % Power

fprintf('Power: %.2f watts\n', P);

Matrices and Arrays

MATLAB is built around matrices. Even scalars are treated as 1x1 matrices. This is particularly useful for electrical engineering applications like solving systems of linear equations in circuit analysis.

Matrix Operations
% Creating matrices
A = [1 2 3; 4 5 6; 7 8 9]  % 3x3 matrix
B = [1 0 0; 0 1 0; 0 0 1]  % Identity matrix

% Matrix operations
C = A + B      % Matrix addition
D = A * B      % Matrix multiplication
E = A .* B     % Element-wise multiplication
F = A'         % Transpose

% Special matrices for EE
Z = zeros(3, 3)  % Matrix of zeros (useful for initialization)
O = ones(2, 4)   % Matrix of ones
R = rand(3, 3)   % Random matrix (for simulations)

% Solving linear equations: A*x = b
A = [3, 2; 1, 4];
b = [5; 6];
x = A\b  % Solution to linear system
fprintf('Solution: x1 = %.2f, x2 = %.2f\n', x(1), x(2))

Array Indexing for Signal Data

% Creating a time vector for signal analysis
t = 0:0.01:1;  % Time from 0 to 1 second in steps of 0.01
f = 5;         % Frequency of 5 Hz
signal = sin(2*pi*f*t);  % Generate sine wave

% Accessing elements
first_value = signal(1)   % First element
last_value = signal(end)  % Last element
segment = signal(1:50)    % First 50 elements

% Finding values in a signal (useful for analyzing peaks)
[max_value, max_index] = max(signal)
fprintf('Maximum value: %.2f at time %.2f seconds\n', ...
        max_value, t(max_index))

Data Visualization

Plotting is essential for electrical engineers to visualize signals, frequency responses, circuit behaviors, and simulation results.

Signal Plotting

Plot Electrical Signals
% Generate and plot a sine wave with noise
t = 0:0.001:0.1;  % 100 ms time vector
f = 60;           % 60 Hz (common electrical frequency)
V = 120*sqrt(2)*sin(2*pi*f*t);  % AC voltage signal
noise = 10*randn(size(t));      % Random noise
V_noisy = V + noise;            % Noisy signal

% Plotting
figure(1);
subplot(2,1,1);
plot(t, V, 'b-', 'LineWidth', 2);
title('Clean 60 Hz AC Signal');
xlabel('Time (s)');
ylabel('Voltage (V)');
grid on;

subplot(2,1,2);
plot(t, V_noisy, 'r-');
title('Noisy AC Signal (with random noise)');
xlabel('Time (s)');
ylabel('Voltage (V)');
grid on;

Multiple Plots

% Multiple signals on same plot
t = 0:0.01:1;
y1 = sin(2*pi*5*t);
y2 = cos(2*pi*5*t);
y3 = exp(-5*t) .* sin(2*pi*5*t);  % Damped sine wave

figure(2);
plot(t, y1, 'b-', t, y2, 'r--', t, y3, 'g-.', 'LineWidth', 1.5);
legend('Sine', 'Cosine', 'Damped Sine');
title('Multiple Signal Comparison');
xlabel('Time (s)');
ylabel('Amplitude');
grid on;

% For frequency domain analysis (EE important!)
% Use fft() function for Fourier transform

Programming in MATLAB

MATLAB supports standard programming constructs like loops and conditionals, which are essential for implementing algorithms and simulations.

Control Structures

Loops

% For loop example - Calculate resistor power dissipation
resistances = [100, 220, 470, 1000];  % Resistor values in ohms
current = 0.1;  % Current in amperes

fprintf('Power dissipation for I = %.2f A:\n', current);
for i = 1:length(resistances)
    R = resistances(i);
    P = current^2 * R;  % P = I^2 * R
    fprintf('  R = %d ohms: P = %.2f watts\n', R, P);
end

% While loop - Find when capacitor charges to 63%
V_source = 5;       % Source voltage
V_c = 0;            % Initial capacitor voltage
R = 1000;           % Resistance in ohms
C = 1e-6;           % Capacitance in farads
tau = R * C;        % Time constant
t = 0;              % Start time
dt = tau/100;       % Time step

while V_c < 0.63 * V_source
    t = t + dt;
    V_c = V_source * (1 - exp(-t/tau));
end
fprintf('Capacitor reaches 63%% of source voltage at t = %.6f s\n', t);

Conditionals

% If-else statement for component selection
voltage = 12;
current = 0.5;
power = voltage * current;

% Determine resistor wattage rating needed
if power < 0.25
    rating = '1/4 watt';
    resistor_type = 'standard';
elseif power < 0.5
    rating = '1/2 watt';
    resistor_type = 'standard';
elseif power < 1
    rating = '1 watt';
    resistor_type = 'power';
elseif power < 2
    rating = '2 watt';
    resistor_type = 'power';
else
    rating = '5+ watt';
    resistor_type = 'high-power';
end

fprintf('Power dissipation: %.2f W\n', power);
fprintf('Required resistor: %s (%s)\n', rating, resistor_type);

% Switch statement for component type
component = 'capacitor';
switch component
    case 'resistor'
        unit = 'ohms';
    case 'capacitor'
        unit = 'farads';
    case 'inductor'
        unit = 'henries';
    otherwise
        unit = 'unknown';
end
fprintf('The unit for %s is %s\n', component, unit);

Electrical Engineering Applications

MATLAB is extensively used in electrical engineering for circuit analysis, signal processing, control systems, and more. Here are some practical examples.

Circuit Analysis

Solve Circuit Equations
% Solve for currents in a simple circuit
% Using Kirchhoff's Voltage Law
% Circuit with two voltage sources and three resistors
%   V1 - I1*R1 - (I1-I2)*R3 = 0
%   -V2 - I2*R2 - (I2-I1)*R3 = 0

% Define circuit parameters
V1 = 10;  % Volts
V2 = 5;   % Volts
R1 = 100; % Ohms
R2 = 200; % Ohms
R3 = 300; % Ohms

% Set up equations in matrix form: A * I = V
A = [R1+R3, -R3; -R3, R2+R3];
V = [V1; -V2];

% Solve for currents
I = A \ V;
I1 = I(1);
I2 = I(2);

fprintf('Circuit Analysis Results:\n');
fprintf('  I1 = %.4f A\n', I1);
fprintf('  I2 = %.4f A\n', I2);
fprintf('  Current through R3: I1-I2 = %.4f A\n', I1-I2);

% Calculate voltages
VR1 = I1 * R1;
VR2 = I2 * R2;
VR3 = (I1 - I2) * R3;
fprintf('\nVoltage Drops:\n');
fprintf('  VR1 = %.2f V\n', VR1);
fprintf('  VR2 = %.2f V\n', VR2);
fprintf('  VR3 = %.2f V\n', VR3);

Signal Processing

% Filter a noisy signal (common in communications)
Fs = 1000;            % Sampling frequency (Hz)
t = 0:1/Fs:1;         % Time vector
f1 = 50;              % Signal frequency (Hz)
f2 = 120;             % Noise frequency (Hz)

% Create signal with noise
signal = sin(2*pi*f1*t) + 0.5*sin(2*pi*f2*t);
noisy_signal = signal + 0.5*randn(size(t));

% Design a low-pass filter to remove 120 Hz noise
fc = 80;              % Cutoff frequency (Hz)
Wn = fc/(Fs/2);       % Normalized cutoff frequency
[b, a] = butter(6, Wn, 'low');  % 6th order Butterworth filter

% Apply filter
filtered_signal = filtfilt(b, a, noisy_signal);

% Plot results
figure(3);
subplot(3,1,1);
plot(t, signal, 'b-');
title('Original Clean Signal (50 Hz)');
xlabel('Time (s)'); ylabel('Amplitude');
grid on;

subplot(3,1,2);
plot(t, noisy_signal, 'r-');
title('Noisy Signal (with 120 Hz interference + random noise)');
xlabel('Time (s)'); ylabel('Amplitude');
grid on;

subplot(3,1,3);
plot(t, filtered_signal, 'g-');
title('Filtered Signal (after low-pass filter at 80 Hz)');
xlabel('Time (s)'); ylabel('Amplitude');
grid on;

Key MATLAB Toolboxes for Electrical Engineering:

  • Simulink: Model and simulate dynamic systems
  • Signal Processing Toolbox: Analyze and visualize signals
  • Control System Toolbox: Design and analyze control systems
  • Simscape Electrical: Model and simulate electrical systems
  • Communications Toolbox: Design and simulate communication systems