How can I speed up simcape simulation (electrical + thermal) with tight timing constraints?
Show older comments
I have a simulnik + simscape model for a 4 phase buck converter for charging a lead accid battery system.

I am using the lead accid battery cell (I have found in this example: https://www.mathworks.com/help/simscape/ug/lead-acid-battery.html) wired 54 cells in series to get my system that matches the one in real life.
I am using a 4 phase DC DC buck converter with current and voltage regulation to control the charging. The controlers are tuned and run discrete with fixed time intervals. The controllers are either in triggered subsystems or triggered matlab functions to get the discrete functionality. They are triggered from a pulse generator.
The buck converter needs to have the duty cycles shifted 1/4 of the period to get less ripple on the output. I am using a sawtooth generator and transport delay to sinchronize the periods and duty cycles, like in the picture below. Due to the switching frequency being 50 kHz and the load type being a battery I found out that i need to run a very small simulation period (very precise simulation) to not get jumps in sawtooth generated to compare to the duty cycles. The required simulation period turns out to be ca. 1e-8 s or 1000x faster than the switching frequency.

The output of the triangle signal generator is on the picture below.

Because of this the simulation takes a very, very long time (sometimes days).
With regard to the duty cycle the transistor firing also needs to have this kind of resolution, otherwise the current oscilates below and above the setpoint.
Only the duty cycle generation and transistor firing need to have this kind of resolution, and other systems do not.
I have found out that the simulation is faster for the first 1 ms, where the battery relay is disconected in picture 1 and after the relay connects it slows down by a significant margin.
To speed up the simulrion I have tried using taks paralleling in simulink, but I cound not get it to work and Matlab uses only max 15 % of the CPU. I am also aware that parallening is difficult to implement with simcape blocks.
The second thing I have tried is using a different battery block / model. More specific the simcape electrical battery model. But I do not know how to correctly fill in the parameters and it did not behave correctly. This would speed up the simulation, because it would not include the thermal considerations of the model only electrical.
So my question are:
1) Is there a way to enable Matlab to use the whole cpu with my system? The current one a I see it uses only 1 thread no matter what setting I change.
2) If you know the parametes for the simcape battery block I could use to implement 54 lead acid cells in series please le me know, so the simulaion would be faster by default.
3) Is there a way solve the very precise duty while increasing the simultion period?
4) Are there any other ways to speed up the simulation? (I still nee scopes to see the results in real time to modify the controllers)
5) Are there any lead accid battery models that do not include thermals online, since I only need it for proof of concept?
Thank you in advance.
Answers (1)
Umar
on 10 Feb 2026
Edited: Walter Roberson
on 10 Feb 2026
0 votes
Hi Mina,
Thanks for reaching out about your 4-phase buck converter simulation challenges. I've reviewed your model setup with the sawtooth generator and transport delay approach for phase-shifted PWM, the 54-cell lead-acid battery from the Simscape thermal example, and the significant slowdown you're experiencing after the relay connects, and I have comprehensive solutions to address all five of your questions. Regarding CPU utilization, unfortunately parallel computing won't help since Simulink runs single simulations in a single thread regardless of settings, which is why you're seeing only 15% CPU usage, and the Parallel Computing Toolbox is designed for running multiple simulations simultaneously rather than parallelizing one simulation, but what will help is switching to Accelerator or Rapid Accelerator mode in Model Configuration Parameters which compiles your model to C code and can provide 2-10x speedups. For your battery parameters question, you can use the Simscape Electrical Battery block (not the thermal example you're currently using) and configure it with 54 series cells, 2V nominal per cell for 108V total, your actual capacity in Ah, and internal resistance of 0.001-0.01 ohms per cell depending on capacity, and critically you should set the Thermal port parameter to None which eliminates the thermal calculations that are likely causing your relay-connection slowdown while maintaining electrical accuracy, or alternatively you can find simpler electrical-only lead-acid models on MATLAB File Exchange such as the SAE 2007-01-0778 battery model used in the Automotive Electrical System example or build your own RC equivalent circuit with a voltage source, series resistance, RC branches, and SOC integrator. Your PWM generation issue is the core problem, and instead of using sawtooth generators with transport delays that require 1e-8s resolution to avoid jumps, you should switch to the built-in PWM Generator (DC-DC) block from Simscape Electrical which handles internal timing efficiently without requiring you to resolve the sawtooth waveform, or for even better speed use the Buck Converter block's "Average model (D-controlled)" setting which eliminates PWM generation entirely and directly uses duty cycle signals while still simulating realistic dynamics perfect for proof-of-concept work, or implement a multirate approach with Rate Transition blocks so PWM runs at higher frequency while battery and controllers run slower, or adjust to a fixed-step solver at 2e-6s (10x your switching frequency) with ode4 and add hysteresis to your comparators to tolerate coarser steps. For additional speedup strategies beyond these, run the Solver Profiler (under Analysis menu) to identify which blocks cause the most solver resets and zero crossings since the relay connection likely introduces zero-crossing events that slow everything down, enable Simulink Cache to reuse unchanged portions, reduce real-time scopes by using decimation or logging to workspace for post-processing, convert stable subsystems to referenced models in Accelerator mode, check for "abs" blocks or other sources of chatter that cause oscillations, and ensure your discrete controllers use appropriate sample times since mixing continuous and discrete blocks incorrectly creates bottlenecks. For online battery models without thermals, check MATLAB File Exchange for "lead acid battery" where you'll find several simplified electrical models, or use the legacy Battery block from Specialized Power Systems library (being removed in R2026a but still functional) which provides lead-acid chemistry without thermal modeling, or reference SAE Paper 2007-01-0778 which describes a simple physical lead-acid model used in MathWorks examples. The simulation slowdown after relay connection is almost certainly due to the thermal battery model creating stiff differential equations and zero-crossing events when the load connects, so switching to an electrical-only battery model and using the PWM Generator block instead of your sawtooth approach should together reduce your simulation time from days to minutes, and as an immediate action sequence I'd recommend first switching to Rapid Accelerator mode, second replacing the thermal battery with the Simscape Electrical Battery block with Thermal port set to None, third replacing your sawtooth generators with PWM Generator (DC-DC) blocks or using the Buck Converter average model, and fourth running the Solver Profiler to verify the improvements and identify any remaining bottlenecks.
5 Comments
Walter Roberson
on 10 Feb 2026
Paragraphs would be appreciated!
Miha
on 10 Feb 2026
Hi @Miha,
Thanks for clarifying - you're absolutely right about the PWM Generator (DC-DC) block not having phase offset, and yes, the SAE battery model does include thermal effects. Let me answer your three questions directly.
Question 1 - PWM with phase selection:
No, there's no standard PWM Generator (DC-DC) block with phase offset like you need. But you have two good options:
If you have SoC Blockset, use the PWM Interface block - it has a "Phase offset in degree" parameter where you can set 0 degrees, 90 degrees, 180 degrees, 270 degrees for your four phases. This eliminates the sawtooth generator completely and runs much faster.
If you don't have SoC Blockset, use a MATLAB Function block with a digital counter. Instead of generating a sawtooth waveform, just use integer counters that increment each timestep. When counter plus phase offset is less than duty cycle counts, output is high, otherwise low. This runs at discrete sample time of 2e-6s instead of your current 1e-8s, so 200x coarser timestep with zero quantization jumps. I can provide the exact code if you want.
Question 2 - Buck converter block efficiency:
Yes,the average buck converter model would be computationally more efficient than discrete switching elements. The reason is not the parameters themselves, but because it eliminates the switching events - no zero-crossings when MOSFETs and diodes turn on/off, no discontinuities in current derivatives. Even though you could mathematically calculate diode current from input/output currents, the discrete switching components create many solver events that slow things down, while the average model uses smooth algebraic equations.
But you're completely right to keep discrete components for your case. You need the actual diode current waveforms for your report, not calculated approximations, and you need accurate modeling of all the component resistances for real efficiency estimation. The speedup from fixing PWM generation will be much more significant anyway.
Question 3 - Battery V1 and AH1 parameters:
For your 54 cell, 800Ah lead-acid battery, set V1 to 95V and AH1 to 160Ah. The logic is that V1 should be about 88% of nominal voltage (108V times 0.88 = 95V) and AH1 should be about 20% of capacity (800Ah times 0.20 = 160Ah). These parameters define a reference point on the discharge curve - when the battery has 160Ah remaining, the open-circuit voltage will be 95V. This matches typical lead-acid discharge characteristics.
Most importantly, set the Thermal port parameter to "None" - this eliminates all the thermal calculations that are slowing down your simulation after the relay connects.
For the other settings: 54 cells series, 108V nominal, 800Ah capacity, internal resistance around 0.04 ohms total.
Implementation Order
Replace your sawtooth PWM generation with either the PWM Interface blocks or the digital counter approach, then swap the battery model to Simscape Electrical Battery with the parameters above and thermal port disabled, then change your solver to fixed-step ode4 at 2e-6s timestep. You should see your simulation time drop from days to a few hours while keeping all the component detail you need for your report.
Miha
on 11 Feb 2026
Hi @Miha,
I have reviewed your latest comments about the errors you're encountering, and I can explain what's happening and provide you with a working solution.
Part 1 WHY THE PWM INTERFACE BLOCK FAILED
The three error messages you're seeing all point to the same root cause: the PWM Interface block is designed for hardware-in-the-loop simulation workflows and has specific requirements that conflict with your setup.
Error 1 “PWM Interface block cannot be used with Fixed-Step Solvers",means block requires variable-step solvers
Error 2: "Cannot compile diagram because it contains variable sample times" means Incompatible with Accelerator mode when using fixed-step
Error 3 "SimEvents block that does not support generating code"means Incompatible with Rapid Accelerator mode
Sine you need fixed-step solvers for Rapid Accelerator mode (which gives you the speed) and for your Simscape components (battery and buck converter), the PWM Interface block simply won't work for your application. I apologize for not catching this compatibility issue earlier - that block is really meant for eventual hardware deployment on microcontrollers like TI C2000 or Infineon AURIX, not for pure simulation speedup.
Bottom line, Abandon the PWM Interface block approach. It's the wrong tool for your use case.
Part 2 YOUR NaN ERROR WITH THE SIMULINK PWM BLOCK
You mentioned getting a NaN error when trying the Simulink PWM block because your duty cycle calculation is: duty = Uo/Uin
At simulation time t=0, before your system powers up, Uin = 0, which causes division by zero means NaN.
The fix is simple - add a Saturation block before your duty cycle calculation:
Insert a Saturation block on your Uin signal
Set the lower limit to 0.1 (or any small positive value like 1.0)
Set the upper limit to inf
Now calculate: duty = Uo / Uin_saturated
This prevents the division by zero and your PWM block will work correctly.
Part 3 WHY SWITCHING TO DISCRETE DELAY WON'T HELP
You mentioned trying to replace Transport Delay with Discrete Delay. Unfortunately, this won't solve your quantization staircase problem.
The real issue isn't the delay block type - it's that your sawtooth generator creates an analog waveform that needs to be sampled at 1e-8 seconds to avoid quantization jumps. Both Transport Delay and Discrete Delay will still require the sawtooth to be sampled this finely.
Think of it this way: if you're trying to draw a smooth ramp from 0 to 1, and you only have 10 samples, you'll see a staircase. The delay block isn't creating the staircase - the coarse sampling of the ramp is.
The solution is to eliminate the analog sawtooth generator entirely and replace it with digital counters - just like how real hardware PWM peripherals work.
Part 4 THE WORKING SOLUTION - DIGITAL COUNTER METHOD
This is the approach that will solve all your problems and give you the 50x speedup you need.
What you will do
Replace your sawtooth generators and transport delays with a single MATLAB Function block that implements digital counters.
How it works
Instead of generating an analog sawtooth waveform (0 → 1) and comparing it to duty cycle, you use integer counters (0 → 100 counts) and compare them to duty cycle counts. This is exactly how real microcontroller PWM peripherals work.
Why this eliminates the quantization problem:
No analog waveform that needs fine sampling
Just integer counting and comparison
No interpolation issues
Exact phase control through counter initialization
Step by Step implementation
Step 1 Create a MATLAB Function Block
In your Simulink model, add a MATLAB Function block from the User-Defined Functions library
Name it something like "PWM_Generator_4Phase"
Step 2: Copy This Exact Code Into the Block (please see attached script)
Step 3: Configure the Block
Double click the MATLAB Function block
The code editor will open - paste the code above
Close the editor
Right click the block → Block Parameters
Set Sample time to: 2e-7
Make sure "Treat as atomic unit" is checked
Click OK
Step 4: Connect Your Signals
Input ports (4 inputs): Connect your duty cycle signals D1, D2, D3, D4 from your controllers
There should be values between 0 and 1 (like 0.5 for 50% duty cycle)
Output ports (4 outputs): Connect S1, S2, S3, S4 to wherever you currently connect your PWM signals (probably to your MOSFET gate signals after the multiplication by 20 and convert blocks)
Step 5: Remove Old Blocks
Delete your sawtooth generators
Delete your transport delay blocks
Delete the comparators that were comparing sawtooth to duty cycle
Step 6 Update Your Solver Settings
Go to Model Configuration Parameters (Ctrl+E)
Solver tab:
Type: Fixed-step
Solver: ode4 (Runge-Kutta)
Fixed-step size: 2e-7
Code Generation tab:
System target file: Keep as Rapid Accelerator
Click OK
Step 7: Build and Run
Click the "Build Model" button (this compiles your Rapid Accelerator target)
Once built, run your simulation
Your simulation should now run much faster
PART 5: UNDERSTANDING THE PERFORMANCE GAIN
Current timestep: 1e-8 seconds (10 nanoseconds) New timestep: 2e-7 seconds (200 nanoseconds) Speed improvement: 20x from timestep alone
But you also get efficiency improvements because:
No analog sawtooth waveform generation overhead
No continuous interpolation calculations
Just simple integer arithmetic
Better cache performance in compiled code
Combined with your battery thermal model removal:
Original: Days
After battery fix: Hours
After PWM fix: 10-20 minutes
Total speedup: approximately 2000-3000x
PART 6: TROUBLESHOOTING (IF NEEDED)
Problem: "All four PWM outputs are synchronized, no phase shift" Solution: Verify the MATLAB Function block sample time is exactly 2e-7 (not -1 or inherited)
Problem: "Getting errors about uint8 data type" Solution: Make sure the %#codegen directive is at the top of your function
Problem: "Simulation is still taking hours" Solution: Check that your fixed-step size in solver settings is 2e-7, not auto-calculated
Problem: "Output current is rippling more than before" Solution: You may need finer PWM resolution. Change PWM_COUNTS from 100 to 200:
Change the line: PWM_COUNTS = 100; to: PWM_COUNTS = 200;
Change phase offsets: counter2 = uint8(50), counter3 = uint8(100), counter4 = uint8(150)
Change sample time to: 1e-7
This gives you 200 steps per PWM period instead of 100
PART 7: ALTERNATIVE SIMPLER SOLUTION (IF YOU PREFER)
If you're not comfortable with MATLAB Function blocks, here's a simpler approach using built-in Simulink blocks:
Use Four Simulink PWM Blocks (from Discontinuities library):
Phase 1 PWM Block:
Period (s): 20e-6
Initial Delay: 0
Run at fixed time intervals: ON
Sample Time: 2e-6
Phase 2 PWM Block:
Period (s): 20e-6
Initial Delay: 5e-6
Run at fixed time intervals: ON
Sample Time: 2e-6
Phase 3 PWM Block:
Period (s): 20e-6
Initial Delay: 10e-6
Run at fixed time intervals: ON
Sample Time: 2e-6
Phase 4 PWM Block:
Period (s): 20e-6
Initial Delay: 15e-6
Run at fixed time intervals: ON
Sample Time: 2e-6
Connect your duty cycle signals directly to each PWM block's input. Remember to fix the NaN error with the Saturation block as described in Part 2.
This approach is easier to implement but gives you 200x speedup instead of the 20x from the digital counter method. It still uses some internal analog generation, so it can't run quite as fast.
SUMMARY
PWM Interface block won't work - it requires variable-step solvers
Fix your NaN error with a Saturation block (lower limit 0.1)
Don't waste time switching to Discrete Delay - it won't help
Implement the digital counter method (MATLAB Function code provided above)
Expected result: Your simulation drops from hours to 10-20 minutes
You have already done the hard work with the battery swap and getting Rapid Accelerator mode working. This PWM fix is the final piece that will get you the performance you need to complete your project.
Categories
Find more on Sources in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!