You are absolutely right! My apologies. That is a classic MATLAB structural error.
MATLAB requires that in a script file (.m file), all local function definitions must appear at the very end of the file. No other executable code can come after them.
There are two excellent ways to fix this.
Solution 1: The Recommended Method (Separate Files)
This is the most common and robust way to organize MATLAB code. You create one file for your main script and a separate file for each helper function.
Step 1: Create a file named windy_gridworld.m and paste the following code into it.
% windy_gridworld.m
% Main script for the Windy Gridworld problem using SARSA
clc;
clear;
close all;
%% --- Parameters ---
% Gridworld parameters
rows = 7;
cols = 10;
start_pos = [4, 1];
goal_pos = [4, 8];
% Wind strength for each column (0=no wind, 1=up 1, 2=up 2)
wind = [0, 0, 0, 1, 1, 1, 2, 2, 1, 0];
% Reinforcement Learning parameters
alpha = 0.5; % Learning rate
gamma = 1.0; % Discount factor (undiscounted for shortest path)
epsilon = 0.1; % Epsilon for epsilon-greedy policy
episodes = 200; % Total number of episodes to run
% Actions: 1:Up, 2:Down, 3:Left, 4:Right
actions = [-1, 0; % 1: Up
1, 0; % 2: Down
0,-1; % 3: Left
0, 1]; % 4: Right
num_actions = size(actions, 1);
%% --- Initialization ---
% Initialize Q-table with zeros: Q(row, col, action)
Q = zeros(rows, cols, num_actions);
steps_per_episode = zeros(episodes, 1);
fprintf('Running SARSA for %d episodes...\n', episodes);
%% --- SARSA Main Loop ---
for ep = 1:episodes
% Initialize state (S)
state = start_pos;
% Choose first action (A) using policy derived from Q (e.g., epsilon-greedy)
action_idx = epsilon_greedy(Q, state, epsilon, num_actions);
steps = 0;
% Loop for each step of episode, until agent reaches the goal
while ~isequal(state, goal_pos)
% Take action A, observe R, S'
% 1. Determine next state based on action
next_state = state + actions(action_idx, :);
% 2. Apply the wind effect
current_wind = wind(state(2)); % Get wind for the current column
next_state(1) = next_state(1) - current_wind; % Wind pushes up (reduces row index)
% 3. Enforce grid boundaries
next_state(1) = max(1, min(rows, next_state(1)));
next_state(2) = max(1, min(cols, next_state(2)));
% 4. Get reward
reward = -1; % -1 for every step that is not the goal
% Choose next action (A') from next state (S') using policy
next_action_idx = epsilon_greedy(Q, next_state, epsilon, num_actions);
% Update Q-value for the state-action pair (S, A)
% SARSA update rule: Q(S,A) <- Q(S,A) + alpha * [R + gamma*Q(S',A') - Q(S,A)]
q_current = Q(state(1), state(2), action_idx);
q_next = Q(next_state(1), next_state(2), next_action_idx);
Q(state(1), state(2), action_idx) = q_current + alpha * (reward + gamma * q_next - q_current);
% Update state and action for the next iteration
state = next_state;
action_idx = next_action_idx;
steps = steps + 1;
% Safety break for very long episodes
if steps > 5000
break;
end
end
steps_per_episode(ep) = steps;
end
fprintf('Training finished.\n');
%% --- Plotting Results ---
figure;
plot(1:episodes, steps_per_episode, 'LineWidth', 2);
xlabel('Episode');
ylabel('Steps per Episode');
title('SARSA Learning Curve on Windy Gridworld');
grid on;
ylim([0, max(steps_per_episode(20:end)) * 1.1]); % Adjust y-axis for better view
Step 2: Create a second file named epsilon_greedy.m in the same folder and paste this code into it.
% epsilon_greedy.m
% Chooses an action using an epsilon-greedy policy
function action_idx = epsilon_greedy(Q, state, epsilon, num_actions)
% With probability epsilon, choose a random action
if rand() < epsilon
action_idx = randi(num_actions);
% Otherwise, choose the best action (greedy)
else
[~, action_idx] = max(Q(state(1), state(2), :));
% If max returns multiple equal values, it picks the first one.
% For this problem, that's fine.
end
end
Now, when you run windy_gridworld.m, it will automatically find and use the epsilon_greedy.m function.
Solution 2: The Single-File Method (Corrected)
If you prefer to keep everything in one file, you just need to ensure the function block is at the absolute end. The code below is a single, self-contained script that will run correctly.
% Windy Gridworld using SARSA in a single script
clc;
clear;
close all;
%% --- Parameters ---
% Gridworld parameters
rows = 7;
cols = 10;
start_pos = [4, 1];
goal_pos = [4, 8];
% Wind strength for each column (0=no wind, 1=up 1, 2=up 2)
wind = [0, 0, 0, 1, 1, 1, 2, 2, 1, 0];
% Reinforcement Learning parameters
alpha = 0.5; % Learning rate
gamma = 1.0; % Discount factor (undiscounted for shortest path)
epsilon = 0.1; % Epsilon for epsilon-greedy policy
episodes = 200; % Total number of episodes to run
% Actions: 1:Up, 2:Down, 3:Left, 4:Right
actions = [-1, 0; % 1: Up
1, 0; % 2: Down
0,-1; % 3: Left
0, 1]; % 4: Right
num_actions = size(actions, 1);
%% --- Initialization ---
% Initialize Q-table with zeros: Q(row, col, action)
Q = zeros(rows, cols, num_actions);
steps_per_episode = zeros(episodes, 1);
fprintf('Running SARSA for %d episodes...\n', episodes);
%% --- SARSA Main Loop ---
for ep = 1:episodes
state = start_pos;
action_idx = epsilon_greedy(Q, state, epsilon, num_actions);
steps = 0;
while ~isequal(state, goal_pos)
next_state = state + actions(action_idx, :);
current_wind = wind(state(2));
next_state(1) = next_state(1) - current_wind;
next_state(1) = max(1, min(rows, next_state(1)));
next_state(2) = max(1, min(cols, next_state(2)));
reward = -1;
next_action_idx = epsilon_greedy(Q, next_state, epsilon, num_actions);
q_current = Q(state(1), state(2), action_idx);
q_next = Q(next_state(1), next_state(2), next_action_idx);
Q(state(1), state(2), action_idx) = q_current + alpha * (reward + gamma * q_next - q_current);
state = next_state;
action_idx = next_action_idx;
steps = steps + 1;
end
steps_per_episode(ep) = steps;
end
fprintf('Training finished.\n');
%% --- Plotting Results ---
figure;
plot(1:episodes, steps_per_episode, 'LineWidth', 2);
xlabel('Episode');
ylabel('Steps per Episode');
title('SARSA Learning Curve on Windy Gridworld');
grid on;
ylim([0, max(steps_per_episode(20:end)) * 1.1]);
%% --- LOCAL FUNCTION DEFINITION ---
% NOTE: This MUST be at the end of the script file.
function action_idx = epsilon_greedy(Q, state, epsilon, num_actions)
% With probability epsilon, choose a random action
if rand() < epsilon
action_idx = randi(num_actions);
% Otherwise, choose the best action (greedy)
else
[~, action_idx] = max(Q(state(1), state(2), :));
end
end