1. What is MATLAB?

So first of all, we should know about MATLAB abbreviation, so it stands for MATrix LABoratory. It is a high-level programming language and interactive environment designed for:

  • Numerical computation (e.g., solving equations, matrix operations)
  • Data analysis and visualization (e.g., sensor test data plots)
  • Algorithm development (e.g., control strategies)
  • Control systems & signal processing
  • Simulink integration & auto code generation

If we talk about in automotive sector, MATLAB is widely used in different area:

  • Model-Based Development (MBD) with Simulink
  • Simulation & test automation
  • Data post-processing (e.g., ECU logs)
  • Hardware-in-the-loop (HIL) testing scripts

2. What is MATLAB Scripting?

  • A MATLAB script is a .m file that containing a sequence of MATLAB commands executed line-by-line.
  • Uses:
    • Automating repetitive tasks
    • Running simulations (MIL/SIL/PIL workflows)
    • Analyzing sensor/test data
    • Generating plots & reports
    • Controlling Simulink models programmatically

Example:
A script engine_analysis.m might load ECU logs, filter noise, and plot fuel injection data.


3. Basic Syntax Rules

Basic Syntax

  • Indexing: A(2,1) โ€“ Access row 2, col 1
  • Range: 1:0.5:5 โ€“ [1 1.5 2 … 5]
  • Functions: mean(x), max(x), sum(x)

Common Commands


4. Variable Assignments

5. Basic Operations

Arithmetic:

Element-wise Operations:


6. Control Flow Statements

% IF-ELSE statement
if x > 5
disp('x is greater than 5');
elseif x == 5
disp('x is 5');
else
disp('x is less than 5');
end
% FOR loop
for i = 1:5
fprintf('Iteration %d\n', i);
end
% WHILE loop
i = 1;
while i <= 3
disp(i);
i = i + 1;
end

7. Basic Plotting

x = 0:0.1:10; % Create range of x values
y = sin(x); % Calculate sine
plot(x, y); % Plot sine wave
title('Sine Wave'); % Add title
xlabel('Time');
ylabel('Amplitude');
grid on;

Output

Automotive Examples

Battery SOC Calculation

I = [10 9 8 7 6]; % Current (A)
dt = 1; % Time interval (s)
Q = 3600; % Battery capacity (As)
SOC = 100 - cumsum(I*dt)/Q * 100;
plot(SOC); ylabel('SOC (%)'); xlabel('Time (s)');

Engine RPM vs Speed

speed = 0:10:200; % km/h
gear_ratio = 4;
rpm = (speed * 1000 * gear_ratio)/60;
plot(speed, rpm); xlabel('Speed (km/h)'); ylabel('RPM');

8. Saving & Running Scripts

  1. Save your file as myscript.m.
  2. Run it from the command window:

>> myscript

9. Common Mistakes to Avoid

10. Automotive Use Cases of MATLAB Scripting