You are absolutely right! My apologies.
The error message Function definitions in a script must appear at the end of the file. means that in a single .m file that contains both executable script code and local function definitions, all the executable script code must come before any function definitions.
In the previous code, the plotting section was placed after the epsilon_greedy function definition. This violates the rule.
Here is the corrected code with the plotting section moved to the correct location (before the function definition):
% Windy Gridworld using SARSA
clc; clear; close all;
% Gridworld parameters
rows = 7;
cols = 10;
start = [4,1];
goal = [4,8];
% Wind strength for each column
% Corresponds to movement upwards (decrease in row index)
% wind = [0 0 0 1 1 1 2 2 1 0]; % Original wind
% Correcting wind to be 1-indexed like state(2) and grid columns
wind_map = [0 0 0 1 1 1 2 2 1 0]; % Wind for columns 1 through 10
% RL parameters
alpha = 0.5; % Learning rate
gamma = 1.0; % Discount factor
epsilon = 0.1; % Epsilon-greedy
episodes = 200; % Number of episodes
% Actions: up, down, left, right (change in [row, col])
% Note: row 1 is top, row 'rows' is bottom
actions = [ -1 0; % 1: Up
1 0; % 2: Down
0 -1; % 3: Left
0 1 ];% 4: Right
nA = size(actions,1); % Number of actions
% Q-table: rows x cols x actions
% Initialize Q-values (e.g., to zeros)
Q = zeros(rows, cols, nA);
% To store results
steps_per_episode = zeros(episodes,1);
% --- Main SARSA Loop ---
for ep = 1:episodes
state = start; % Start of the episode
% Choose initial action using epsilon-greedy policy
a = epsilon_greedy(Q, state, epsilon, nA);
steps = 0; % Counter for steps in the current episode
% Loop until the goal is reached
while ~isequal(state, goal)
steps = steps + 1;
% --- Take action and observe next state and reward ---
% Calculate potential next state based on action
next_state_potential = state + actions(a,:);
% Apply wind effect (upward push, i.e., decrease row index)
% Wind strength depends on the current state's column
current_col = state(2);
wind_strength = wind_map(current_col); % Get wind for the current column
next_state_with_wind = next_state_potential;
next_state_with_wind(1) = next_state_with_wind(1) - wind_strength;
% Ensure next state stays within grid boundaries
next_state = next_state_with_wind;
next_state(1) = max(1, min(next_state(1), rows)); % Clamp row
next_state(2) = max(1, min(next_state(2), cols)); % Clamp column
% Define reward
% In simple gridworlds, often -1 for each step until goal
reward = -1;
% --- Choose next action using epsilon-greedy policy ---
% This is the 'A'' part of S(t+1)A(t+1)
next_a = epsilon_greedy(Q, next_state, epsilon, nA);
% --- SARSA Update Rule ---
% Q(S, A) = Q(S, A) + alpha * [R + gamma * Q(S', A') - Q(S, A)]
% Get current Q-value Q(S,A)
q_current = Q(state(1), state(2), a);
% Get next Q-value Q(S',A')
q_next = Q(next_state(1), next_state(2), next_a);
% Calculate TD error
td_error = reward + gamma * q_next - q_current;
% Update Q-value
Q(state(1), state(2), a) = q_current + alpha * td_error;
% --- Move to the next state and action ---
state = next_state; % S(t+1) becomes S(t) for the next iteration
a = next_a; % A(t+1) becomes A(t) for the next iteration
end % End of while loop (episode ends when goal is reached)
% Record steps for this episode
steps_per_episode(ep) = steps;
% Optional: Decrease epsilon over time
% epsilon = epsilon * 0.99; % Example decay
end % End of episodes loop
% --- Plotting Learning Curve ---
% Place plotting code BEFORE local function definitions
figure;
plot(1:episodes, steps_per_episode, 'LineWidth',2);
xlabel('Episode');
ylabel('Steps per Episode');
title('Windy Gridworld: SARSA Learning Curve');
grid on;
% You could add visualization of the learned policy here as well
% --- Helper function: epsilon-greedy policy ---
% This function MUST be defined AFTER all main script code.
function a = epsilon_greedy(Q, state, epsilon, nA)
% epsilon-greedy policy: explores with probability epsilon,
% exploits (picks best action) with probability 1-epsilon.
if rand < epsilon
% Explore: choose a random action
a = randi(nA);
else
% Exploit: choose the action with the highest Q-value for the current state
% Q(state(1), state(2), :) gives the Q-values for all actions in the current state
[~, a] = max(Q(state(1), state(2), :));
% max returns the maximum value and its index. We need the index (action number).
% If there are multiple actions with the same max Q-value,
% max returns the index of the first one. This is acceptable.
% Ensure 'a' is a scalar index
a = squeeze(a);
% Squeeze removes singleton dimensions; useful if max returns a 1x1x1 array
end
end
Reason for the Error:
MATLAB scripts execute sequentially from top to bottom. When the MATLAB interpreter encounters a function definition within a script, it expects only other function definitions (or comments/whitespace) until the end of the file. If it finds any executable script code after the first function definition, it throws the error you saw.
By moving the figure; plot(...) block to be before the function a = epsilon_greedy(...) line, we ensure all script code runs first, and then the local function is defined at the end of the file, satisfying MATLAB's requirement.