You can now store data, calculate with it, and visualise it. But every command runs once when you press Enter — MATLAB cannot yet decide what to do based on a value. A real Battery Management System checks hundreds of conditions every millisecond: is SoC too low? Is temperature too high? Is voltage dropping unexpectedly? That decision-making logic is what Session 4 teaches.
📄
Scripts — Saving and Rerunning Your Work
A script is a plain text file with the extension .m that contains a sequence of MATLAB commands. Instead of typing commands one by one, you write them all in a script, save it, and run the whole file at once.
Diagram — Command Window vs Script
flowchart LR
subgraph CW["Command Window"]
direction TB
A1["Type command"]:::step
A2["Press Enter"]:::step
A3["Result appears"]:::step
A4["Type next command..."]:::step
A1 --> A2 --> A3 --> A4
NOTE1["❌ Nothing saved\n❌ Cannot rerun\n✅ Good for quick tests"]:::note
end
subgraph SC["Script (.m file)"]
direction TB
B1["Write all commands\nin editor"]:::step
B2["Press Run (or F5)"]:::step
B3["All lines execute\nin order"]:::step
B4["Edit → Save → Rerun"]:::step
B1 --> B2 --> B3 --> B4
NOTE2["✅ Saved to disk\n✅ Fully reproducible\n✅ Industry standard"]:::good
end
classDef step fill:#E0F2FE,stroke:#0284C7,color:#0369A1
classDef note fill:#FEE2E2,stroke:#DC2626,color:#991B1B,font-size:11px
classDef good fill:#D1FAE5,stroke:#059669,color:#065F46,font-size:11px
% bms_check.m — Battery Management System threshold script% Always start a script with a comment header explaining what it doesbattery_voltage = 400; % Vsoc = 18; % %motor_temp = 85; % °C% Decision logic goes here...
Comments
Lines starting with % are comments — MATLAB ignores them when running the script. Comments are the engineer's notes inside the code. Always write them. Professional scripts start with a comment header naming the file and describing what it does, and add inline comments explaining the unit of every variable.
Semicolons
Adding ; after an assignment (soc = 18;) suppresses the output in the Command Window. Without semicolons, MATLAB prints every assigned value — useful when debugging, but noisy in production scripts. In Session 4 you will use semicolons after variable definitions and omit them on disp() lines where you actually want output.
⚖️
Logical Operators — The Language of Decisions
A condition is an expression that evaluates to either true (1) or false (0). Logical operators are the building blocks of every condition.
The most important distinction: = vs ==
=
Assignment
Stores a value in a variable
soc = 18 → stores 18 in soc
==
Comparison
Checks if two values are equal — returns true or false
soc == 18 → true if soc is 18, false otherwise
Critical
Using = inside an if condition instead of == is the single most common error in this session. MATLAB will give an error or unexpected behaviour. The rule: = assigns, == compares. Write it on your notes page now.
Diagram — logical operators overview
flowchart LR
subgraph REL["Relational — compare two values"]
direction LR
R1["==\nequal to"]:::rel
R2["~=\nnot equal"]:::rel
R3["<\nless than"]:::rel
R4[">\ngreater than"]:::rel
R5["<=\nless or equal"]:::rel
R6[">=\ngreater or equal"]:::rel
end
subgraph LOG["Logical — combine conditions"]
direction LR
L1["&&\nAND\nboth must be true"]:::log
L2["|\u007C\nOR\neither can be true"]:::log
L3["~\nNOT\nflips true↔false"]:::log
end
classDef rel fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6,font-weight:bold
classDef log fill:#FEF3C7,stroke:#D97706,color:#92400E,font-weight:bold
==
Equal to
soc == 100
true when SoC is exactly 100%
~=
Not equal to
status ~= 0
true when status is not zero
<
Less than
soc < 20
true when SoC is below 20%
>
Greater than
motor_temp > 80
true when temperature exceeds 80°C
&&
AND
soc < 20 && temp > 70
true only when BOTH conditions hold
||
OR
soc < 10 || temp > 90
true when EITHER condition holds
🔀
if / elseif / else — Decision Branching
An if block tells MATLAB: run this code only if a condition is true. Use elseif to check additional conditions and else to catch everything else.
soc = 18;
ifsoc < 20disp('WARNING: Low battery — charge immediately')
elseifsoc < 50disp('NOTICE: Battery at moderate level')
elsedisp('Battery OK')
end% ← every if block must close with end
Rule
Why it matters
Every if needs end
Missing end is the most common structural error — MATLAB will error or behave unexpectedly
elseif is one word
Writing else if (two words) creates a nested if — different behaviour, different requirement for a second end
Only one branch executes
Once a condition is true, MATLAB runs that branch and skips the rest — even if a later condition would also be true
Use separate if for independent checks
A vehicle can have low SoC and overtemperature simultaneously — use two separate if blocks, not elseif
BMS Connection
Every protection threshold in a Battery Management System is an if statement. Low SoC warning, overtemperature cutoff, cell overvoltage, regen braking enable — all of these are conditions evaluated in code that looks exactly like what you wrote above.
🔁
for Loops — Repeating Over Data
A for loop repeats a block of code for each value in a sequence. Use it when you need to process every element of a vector — for example, checking every data point in a sensor log.
Diagram — how a for loop iterates over a vector
flowchart TD
INIT["soc_log = [95, 72, 48, 19, 8]"]:::init
LOOP{"for i = 1 to length(soc_log)"}:::loop
BODY["current_soc = soc_log(i)\nRun code block with current_soc"]:::body
INC["i = i + 1\n(automatic)"]:::inc
CHECK{"i ≤ length?"}:::check
END(["end — loop complete"]):::done
INIT --> LOOP --> BODY --> INC --> CHECK
CHECK -->|"YES — continue"| BODY
CHECK -->|"NO — done"| END
classDef init fill:#F1F5F9,stroke:#94A3B8,color:#1A2B3C
classDef loop fill:#E0F2FE,stroke:#0284C7,color:#0369A1,font-weight:bold
classDef body fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6
classDef inc fill:#F1F5F9,stroke:#94A3B8,color:#1A2B3C,font-size:12px
classDef check fill:#FEF3C7,stroke:#D97706,color:#92400E,font-weight:bold
classDef done fill:#D1FAE5,stroke:#059669,color:#065F46,font-weight:bold
% Basic for loop over a rangefori = 1:5disp(i) % prints 1, then 2, then 3, then 4, then 5end% Loop over every element of a vectorsoc_log = [95, 72, 48, 19, 8];
fori = 1:length(soc_log)
disp(soc_log(i)) % prints each SoC value in turnend
Rule
Detail
Every for needs end
Same rule as if — MATLAB errors without the closing end
Use length(v)
for i = 1:length(soc_log) loops over every element regardless of vector size
Loop variable updates automatically
i increments by 1 each iteration — you do not need to write i = i + 1
Loops can nest if blocks
Put an if/end inside a for/end to check conditions on each element
num2str() — building output messages
When you want to display a number as part of a text message, convert it with num2str() first, then join using square brackets.
i = 3;
current_soc = 48;
% Joining text and numbers — square brackets join stringsdisp(['Second 'num2str(i) ': SoC = 'num2str(current_soc) '%'])
% → Second 3: SoC = 48%
🔗
Combining Loops & Logic — The BMS Pattern
The most powerful pattern in this session is a for loop containing an if/elseif/else block. This structure is the skeleton of real BMS decision-making code.
Diagram — for + if/else nested structure (BMS pattern)
flowchart TD
A["for i = 1 to length(soc_log)"]:::loop
B["current_soc = soc_log(i)"]:::assign
C{"current_soc < 10?"}:::cond
D{"current_soc < 20?"}:::cond
E{"current_soc < 50?"}:::cond
F["CRITICAL"]:::critical
G["WARNING"]:::warning
H["NOTICE"]:::notice
I["OK"]:::ok
J["end — if block"]:::endblock
K["end — for loop\n(next i)"]:::endloop
A --> B --> C
C -->|"true"| F --> J
C -->|"false"| D
D -->|"true"| G --> J
D -->|"false"| E
E -->|"true"| H --> J
E -->|"false"| I --> J
J --> K
classDef loop fill:#E0F2FE,stroke:#0284C7,color:#0369A1,font-weight:bold
classDef assign fill:#F1F5F9,stroke:#94A3B8,color:#1A2B3C
classDef cond fill:#EDE9FE,stroke:#7C3AED,color:#5B21B6,font-weight:bold
classDef critical fill:#FEE2E2,stroke:#DC2626,color:#991B1B,font-weight:bold
classDef warning fill:#FECACA,stroke:#EF4444,color:#7F1D1D
classDef notice fill:#FEF3C7,stroke:#D97706,color:#92400E
classDef ok fill:#D1FAE5,stroke:#059669,color:#065F46,font-weight:bold
classDef endblock fill:#F1F5F9,stroke:#94A3B8,color:#94A3B8,font-size:11px
classDef endloop fill:#F1F5F9,stroke:#94A3B8,color:#94A3B8,font-size:11px
Count ends
When nesting loops and conditionals, count your end keywords. A for/if/end/end structure needs two end keywords — one to close the if and one to close the for. If you get unexpected errors, count your end keywords first.
🔧
Block C Demo + Block D Task
Block C — Instructor Demo: BMS Threshold Script
During Block C your instructor will build the following script live. Follow along in Onramp and replicate it. Then test it with different values as instructed.
Demo script — bms_check.m
% bms_check.m — BMS threshold decision scriptbattery_voltage = 400; % Vsoc = 18; % %motor_temp = 85; % °C% SoC check — three levelsifsoc < 20disp('WARNING: Low battery — charge immediately')
elseifsoc < 50disp('NOTICE: Battery at moderate level')
elsedisp('Battery OK')
end% Temperature check — separate if (can fire independently)ifmotor_temp > 80disp('ALERT: Motor overtemperature — reduce power')
end
After replicating the demo, test with soc = 45 and motor_temp = 72 and predict the output before running.
Two if blocks
The temperature check uses a separateif block, not an elseif. This is deliberate — a vehicle can have low SoC and overtemperature at the same time. Both messages need to fire. If they were in the same if/elseif chain, MATLAB would stop after the first true condition and never evaluate the second.
Block D⏱ 15 minBMS Logic Script with Loop
Write a script in your Onramp session that processes a 5-point SoC log.
1
Define the SoC log vector
Create a variable soc_log holding five SoC readings in percent: [95, 72, 48, 19, 8]. These represent battery readings taken one per second during a drive that clearly ran the battery very low.
2
Write a for loop to process each reading
Using a for loop and length(), iterate over every element of soc_log. Inside the loop, assign each element to a variable called current_soc.
3
Add the decision logic inside the loop
Inside the loop, write an if/elseif/else/end block with four levels based on current_soc:
Below 10 → CRITICAL — imminent shutdown
Below 20 → WARNING — low battery
Below 50 → NOTICE — moderate battery
50 or above → OK
Each output line should include the second number (use num2str(i)) so it is clear which reading triggered which alert.
Close the if block with end, then close the for loop with end. Count your end keywords before running.
4
Run and reflect
Run the script. You should see five output lines — one per second. Then answer the reflection questions below.
Q1 — Which seconds trigger a WARNING or CRITICAL alert? What does the SoC log tell you about this drive?
Hint: check each value in soc_log against your threshold conditions before running
Q2 — Why does the CRITICAL check come before the WARNING check in the if/elseif chain? What would happen if they were swapped?
Hint: a value of 8 satisfies both soc < 10 and soc < 20 — which branch executes first?
Q3 — How would you modify the script to also print the actual SoC value next to each alert message? Which function enables this?
Hint: you used this function earlier in the session to join numbers with text
Q4 — In a real BMS running at 100 Hz, this loop would execute 100 times per second. What would need to change in the script structure if the SoC data were arriving live from a sensor rather than stored in a vector?
Hint: think about how the input to the loop would be structured differently
Note
Work through the logic yourself. The structure diagram above is a guide, not a solution. If you get stuck, reread the for loops and if/else sections before asking for help.
Troubleshooting — if something goes wrong
❌ if soc = 20 — assignment error in condition
Cause: Single = used instead of == or a relational operator
Fix:= assigns, == compares. Inside if conditions use ==, <, >, etc. — never a single =.
❌ Script errors or only the first branch ever runs
Cause: Missing end keyword for the if block, the for loop, or both
Fix: Count your end keywords — you need one for the if block and one for the for loop (two total). Use indentation to see the structure clearly.
❌ elseif not recognised / unexpected behaviour
Cause: Written as else if (two words) instead of elseif (one word)
Fix: In MATLAB elseif is a single keyword. else if creates a nested if inside else — different structure, different end requirement.
⚠️ CRITICAL alert never fires
Cause: CRITICAL condition placed after WARNING in the if/elseif chain
Fix: Order matters — put the most specific (smallest) threshold first. if soc < 10 must come before elseif soc < 20.
⚠️ num2str() error
Cause: num2str() called with a string variable instead of a number
Fix: Ensure you are passing a numeric variable to num2str(). Use class(variable) to check — it should return 'double'.
🔍 Only one output line appears (not five)
Cause:for loop range is wrong — e.g. for i = 1:1 instead of for i = 1:length(soc_log)
Fix: Use length(soc_log) in the loop range to ensure it iterates once per element.
🏆 Certificate not appearing after completing all modules
Cause: One or more Onramp exercises not fully submitted
Fix: Check the Onramp progress bar — all modules must show 100%. Find incomplete exercises and submit them. Then go to learn.mathworks.com → My Courses → MATLAB Onramp → Get Certificate.
🏆
Key Takeaways + Certificate
🏆
MATLAB Onramp Certificate
Earned at the end of Session 4
✓ Variables & arithmetic
✓ Visualization & plotting
✓ Vectors, arrays & indexing
✓ Scripts, logic & control flow
Complete all MATLAB Onramp exercises before the end of Block C to claim your certificate.
→ learn.mathworks.com · My Courses · MATLAB Onramp · Get Certificate
📄Scripts save sequences of commands in .m files — reproducible, documented, and reusable
%Comments starting with % are the engineer's notes — always add a header comment and document units
⚖️Logical operators (==, <, >, &&, ||) form conditions — the language of decisions. Remember: = assigns, == compares
🔀if/elseif/else/end branches execution — only one branch runs, every if needs a matching end
🔁for loops repeat a block over a range or vector — combine with if/else to process sensor logs element by element
🚗A Battery Management System is essentially a script running thousands of if checks per second — today you built the logical skeleton of one
Looking ahead — Sessions 5–8: Simulink
The MATLAB Onramp is now 100% complete. Starting Session 5, you will move to Simulink Onramp — a completely different way of working. Instead of typing code, you will build graphical block diagrams where signals flow between components.
Think about how a motor, battery, and controller would connect as blocks in a diagram, with signals (voltage, current, speed) flowing along the wires between them. That is exactly what Simulink models.