How to Use MATLAB for Electrical Circuit Analysis

How to Use MATLAB for Electrical Circuit Analysis

Electrical circuit analysis can be straightforward when you are dealing with a simple resistor network. Things become different when a circuit contains several nodes, capacitors, inductors, AC sources, or multiple operating conditions. At that point, doing every calculation manually can take a considerable amount of time, and it becomes easier to make a small mistake that affects the final answer.

This is where MATLAB becomes useful.

I like to think of MATLAB as a connection between the circuit equations you learn in electrical engineering and the results you actually need to obtain. You can use it to solve simultaneous equations, work with complex numbers, simulate changing signals, and turn a collection of numerical results into useful graphs.

The important point is that MATLAB does not replace circuit theory. You still need to understand what the circuit is doing. MATLAB simply gives you a practical way to handle the mathematics and investigate the results.

Why MATLAB Is Useful for Circuit Analysis

The basic principles of circuit analysis have not changed. Kirchhoff’s Current Law (KCL), Kirchhoff’s Voltage Law (KVL), Ohm’s law, and the relationships between voltage, current, resistance, capacitance, and inductance are still the starting point.

What changes is how much work you have to do by hand.

Imagine a circuit that produces four or five simultaneous equations. You could solve those equations manually, but MATLAB can handle the system almost immediately. You can then change a component value and run the calculation again without starting from scratch.

MATLAB is particularly useful when you need to:

  • Solve several circuit equations simultaneously.
  • Perform nodal or mesh analysis.
  • Calculate AC impedance and phasor quantities.
  • Investigate capacitor and inductor transients.
  • Plot voltage and current against time.
  • Examine how a circuit responds to different frequencies.
  • Repeat calculations for different component values.
  • Compare theoretical results with simulation results.

That last point is especially important for students. A graph often makes a circuit’s behaviour much easier to understand than a page of equations.

Setting Up MATLAB for Electrical Calculations

You can perform most basic circuit calculations in an ordinary MATLAB script. For assignments and lab work, I also find MATLAB Live Scripts useful because they allow code, explanations, equations, results, and graphs to sit in the same document.

MathWorks provides documentation for creating and working with Live Scripts, which can be useful when you need to present your calculation rather than simply produce a numerical answer.

A simple resistor calculation might look like this:

clc

clear

R1 = 1000; % Resistance in ohms

R2 = 2000; % Resistance in ohms

Vs = 5; % Source voltage

Rtotal = R1 + R2;

I = Vs / Rtotal;

fprintf(‘Total resistance: %.2f ohms\n’, Rtotal)

fprintf(‘Current: %.6f A\n’, I)

There is nothing complicated here. The total resistance is 3 kΩ, giving a current of approximately 1.67 mA.

What matters is the habit of defining your variables clearly and keeping your units consistent.

For example, if a resistor is 4.7 kΩ, enter it as:

R = 4.7e3;

rather than simply typing 4.7.

MATLAB will not know that your 4.7 was supposed to represent thousands of ohms.

Solving Circuit Equations With MATLAB

One of the biggest advantages of MATLAB appears when a circuit produces simultaneous equations.

Suppose nodal analysis gives you:

2V1−V2=5

and

−V1+3V2=4

These equations can be written as:

AV=b

where:

A=[2−1−13]

and

b=[54]

In MATLAB, you can solve the system like this:

A = [2 -1;

 -1 3];

b = [5;

 4];

V = A\b;

disp(V)

The \ operator is particularly useful in circuit analysis. Instead of calculating a matrix inverse yourself, you tell MATLAB directly that you want to solve the system AV=b.

MathWorks recommends matrix left division for solving systems of linear equations, and its behaviour is documented in the MATLAB mldivide documentation.

You may sometimes see code such as:

V = inv(A)*b;

For a standard linear system, I would normally use A\b instead. It is simpler and expresses the mathematical problem more directly.

Using MATLAB for Nodal Analysis

Nodal analysis is particularly well suited to MATLAB because the equations naturally form a matrix.

The process is much the same as it would be on paper:

  1. Choose a reference node.
  2. Assign a voltage variable to each remaining node.
  3. Apply KCL at each node.
  4. Rearrange the equations.
  5. Put the coefficients into a matrix.
  6. Solve the matrix in MATLAB.
  7. Use the node voltages to calculate the branch currents you need.

The advantage becomes obvious when the number of nodes increases.

For a two-node circuit, you may not need MATLAB at all. With ten or twenty unknown voltages, however, manually solving every equation becomes much less attractive.

You can also use MATLAB’s Symbolic Math Toolbox when you need symbolic rather than purely numerical solutions. MathWorks provides solve for solving equations and systems of equations symbolically.

A Simple Voltage Divider Example

Let’s use a familiar circuit to see how MATLAB can do more than calculate one answer.

Suppose you have a 12 V supply connected to two resistors:

  • R1=4 kΩ
  • R2=2 kΩ

The circuit current is:

I=VsR1+R2

The voltage across R2 is:

V2=IR2

In MATLAB:

Vs = 12;

R1 = 4e3;

R2 = 2e3;

I = Vs/(R1 + R2);

V2 = I*R2;

fprintf(‘Current = %.3f mA\n’, I*1000)

fprintf(‘Voltage across R2 = %.2f V\n’, V2)

The current is 2 mA and the voltage across the second resistor is 4 V.

But we can take the example further.

Instead of calculating the output voltage for one value of R2, let’s examine what happens as R2 changes:

R2 = linspace(100,10000,200);

V2 = Vs .* R2 ./ (R1 + R2);

plot(R2,V2,’LineWidth’,1.5)

xlabel(‘R_2 (Ohms)’)

ylabel(‘Output Voltage (V)’)

title(‘Voltage Divider Response’)

grid on

Now you have a visual representation of the circuit’s behaviour.

This is one of the areas where MATLAB becomes more interesting than a calculator. You are no longer asking, “What is the voltage for this one resistor?” You are asking, “How does the circuit behave across a range of resistor values?”

MATLAB’s plot function is designed for exactly this kind of two-dimensional visualization.

Working With AC Circuits and Complex Impedance

AC circuit analysis introduces another reason to use MATLAB: complex numbers.

For a resistor:

ZR=R

For a capacitor:

ZC=1jωC

And for an inductor:

ZL=jωL

where:

ω=2πf

If you have done these calculations by hand, you know that keeping track of real and imaginary parts can become tedious. MATLAB handles complex values directly.

For example:

R = 100;

C = 10e-6;

f = 1000;

w = 2*pi*f;

ZR = R;

ZC = 1/(1j*w*C);

Ztotal = ZR + ZC;

fprintf(‘Total impedance = %.2f + j%.2f Ohms\n’, …

 real(Ztotal), imag(Ztotal))

You can then find the magnitude and phase:

Zmag = abs(Ztotal);

Zphase = angle(Ztotal);

fprintf(‘Magnitude = %.2f Ohms\n’, Zmag)

fprintf(‘Phase = %.2f degrees\n’, rad2deg(Zphase))

This approach can be extended to RLC circuits, filters, phasor calculations, and frequency-response studies.

Simulating Transient Behaviour

Steady-state calculations tell only part of the story.

When a switch is closed or an input suddenly changes, capacitors and inductors produce a transient response. MATLAB is useful here because you can calculate the response over thousands of time points and plot the result.

Consider a basic RC charging circuit.

Its time constant is:

τ=RC

For a capacitor charging from a DC source:

VC(t)=Vs(1−e−t/RC)

The MATLAB code can be written as:

R = 1000;

C = 100e-6;

Vs = 5;

tau = R*C;

t = linspace(0,5*tau,500);

Vc = Vs*(1 – exp(-t/tau));

plot(t,Vc,’LineWidth’,1.5)

xlabel(‘Time (s)’)

ylabel(‘Capacitor Voltage (V)’)

title(‘RC Charging Response’)

grid on

In this example, the time constant is 0.1 seconds.

The graph gives you a much clearer picture of the charging process than the equation alone. You can see the rapid initial rise and the gradual approach toward the supply voltage.

For circuits that produce more complicated differential equations, MATLAB offers symbolic and numerical tools for solving them.

Studying Frequency Response With MATLAB

If you are working with filters, frequency-dependent circuits, or control systems, frequency response is another useful application.

For example, a first-order low-pass circuit can be represented by:

H(s)=1RCs+1

With the Control System Toolbox, you can create this transfer function and display its Bode plot:

s = tf(‘s’);

R = 1000;

C = 100e-6;

H = 1/(R*C*s + 1);

bode(H)

grid on

A Bode plot shows how the magnitude and phase of the system response change with frequency. This makes it easier to identify behaviour such as attenuation, phase shift, and approximate bandwidth.

MathWorks documents bode as a function for plotting the magnitude and phase response of dynamic systems. MATLAB Bode plot documentation

For students studying filters, this can be particularly helpful because you can change R or C, rerun the model, and immediately see how the frequency response moves.

MATLAB vs. Simscape Electrical

There is a difference between using MATLAB to calculate a circuit and using a tool to model the circuit itself.

For relatively small calculations, MATLAB code is often enough. If you want to build a model containing physical electrical components and simulate their interaction, Simscape Electrical is worth looking at.

MathWorks describes Simscape Electrical as an environment for modelling and simulating electrical, electronic, and electromechanical systems. It includes component libraries for sources, electrical elements, sensors, and larger electrical systems. 

For example, you can construct an RC circuit using physical components rather than representing everything as equations in a script.

That can be useful when the circuit becomes too complicated to describe conveniently with a few lines of MATLAB code.

I would not automatically use Simscape for every homework problem, though. If you are calculating the current in a simple series circuit, a few lines of MATLAB are quicker. Choose the tool according to the problem rather than making the problem more complicated than it needs to be.

A Practical Workflow for Circuit Analysis

When I work through a MATLAB circuit problem, I find that a consistent process prevents most avoidable mistakes.

Start with the circuit

Draw the circuit and identify the source, components, nodes, branches, and reference node.

Don’t start coding before you understand what you are trying to calculate.

Choose the analysis method

Decide whether the problem calls for nodal analysis, mesh analysis, impedance calculations, a transfer function, or a time-domain simulation.

Define the component values

Keep your physical parameters near the beginning of the script:

R1 = 1e3;

R2 = 2.2e3;

C = 47e-6;

Vs = 10;

This makes the program easier to modify later.

Build the equations

For a nodal-analysis problem, create the coefficient matrix and source vector.

A = […];

b = […];

Solve the system

For a linear system, use:

x = A\b;

Check the result

Don’t assume that a number printed by MATLAB is automatically correct.

Check whether the units make sense. Look at the sign of the voltage or current. Check KCL or KVL where possible. For a simple circuit, compare the MATLAB result with a hand calculation.

This is one of the most valuable habits you can develop.

Plot the important quantities

If you are studying a transient or parameter variation, create a graph. Trends are often easier to spot visually than numerically.

Keep the work documented

A Live Script can be useful for assignments and laboratory work because your calculations, explanation, code, and figures can remain together rather than being scattered across separate files.

Common MATLAB Mistakes in Electrical Engineering

Most problems I see with MATLAB circuit calculations are not really MATLAB problems. They are modelling or unit problems.

A few are particularly common.

Mixing units is probably the easiest mistake to make. A value of 10 µF should be entered as 10e-6, not 10.

Getting signs wrong is another issue. If you define a current direction one way when creating your equations and another way later, your result can look strange even though MATLAB has solved the equations correctly.

You also need to understand the difference between matrix and element-wise operations. For example:

A * B

and

A .* B

do different things. MATLAB’s documentation explains the distinction between matrix operations and array operations.

AC analysis creates another common source of confusion. Voltage, current, and impedance can be complex quantities, so don’t automatically discard the imaginary part because it “

Below is a more natural, original rewrite with less formulaic phrasing, more varied sentence structure, and a stronger practical/student perspective. I’ve also removed unnecessary repetition and kept the technical explanations accurate. No one can honestly guarantee that a piece will “pass” every AI or plagiarism detector, but this version is written from scratch rather than mechanically paraphrased.

AC analysis creates another common source of confusion. Voltage, current, and impedance can be complex quantities, so don’t automatically discard the imaginary part because it “doesn’t look like a normal number.”

Finally, don’t make a simple circuit unnecessarily complicated. If Ohm’s law gives you the answer in ten seconds, there is no prize for writing fifty lines of MATLAB code.

For larger coursework projects where the coding itself is becoming the difficult part, a MATLAB code assignment service can provide additional assistance with MATLAB programming and debugging. Even then, I would recommend understanding the circuit equations yourself. Getting working code is useful; understanding why the code works is far more valuable in the long run.

Final Thoughts

MATLAB becomes genuinely useful for electrical circuit analysis when you use it to explore a circuit rather than simply produce one number.

Start with the electrical principles. Work out what the circuit is doing, establish your equations, and then use MATLAB to solve, repeat, visualize, and test those equations.

For a simple resistor network, that may mean a short script. For a circuit with several nodes, matrix methods can save a great deal of manual work. Once you move into AC analysis, MATLAB’s ability to handle complex numbers makes impedance and phasor calculations much easier to manage. For transient circuits, plots can show exactly how voltage and current change with time.

And when the model becomes more involved, MATLAB can be combined with tools such as Control System Toolbox, Simulink, and Simscape Electrical.

The biggest advantage is not simply speed. It is the ability to experiment.

Change the resistance. Change the capacitance. Sweep through different frequencies. Extend the simulation time. Plot another variable. Compare your calculated result with the behaviour you expected from circuit theory.

Leave a Comment