give me a Matlab code for cliff walking problem in reinforcement learning, for both Q learning and Sarsa, animate agent pass and show the best episode solution
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Here is a comprehensive MATLAB script for the Cliff Walking problem. This single script includes implementations for both Q-Learning and SARSA, animates the agent's learning process, and displays the final optimal path found by each algorithm.
Key Concepts in this Code
The Environment (Cliff Walking):
A 4x12 grid.
Start: Bottom-left corner.
Goal: Bottom-right corner.
The Cliff: The entire bottom row between the start and goal.
Actions: Up, Down, Left, Right.
Rewards:
-1 for every step in a safe square.
-100 for stepping into the cliff. The episode ends, and the agent is sent back to the start.
Reaching the goal terminates the episode.
Q-Learning (Off-Policy): The agent learns the value of being in a state s and taking action a by observing the outcome (s', r). It then updates its Q-value using the best possible next action from the new state s', regardless of the policy it's actually following. This is why it's "off-policy". It learns the optimal path, which in this case is dangerously close to the cliff edge.
Update Rule: Q(s, a) ← Q(s, a) + α * [r + γ * max_a'(Q(s', a')) - Q(s, a)]
SARSA (On-Policy): The agent learns based on the action it actually takes in the next step. The update rule uses the tuple (s, a, r, s', a'). Because its update rule depends on the action a' chosen by its current (epsilon-greedy) policy, it's "on-policy". This makes it more conservative; it learns a "safer" path that stays away from the cliff because the exploratory (epsilon) moves are too risky near the edge.
Update Rule: Q(s, a) ← Q(s, a) + α * [r + γ * Q(s', a') - Q(s, a)]
MATLAB Code
Copy and paste the following code into a single .m file (e.g., cliff_walking_main.m) and run it.
matlab
% Main script for the Cliff Walking problem using Q-Learning and SARSA
% This script will:
% 1. Define the environment.
% 2. Run the Q-Learning algorithm.
% 3. Run the SARSA algorithm.
% 4. Plot the learning performance (rewards per episode).
% 5. Animate the final, optimal path found by each algorithm.
clear; close all; clc;
% --- 1. ENVIRONMENT AND ALGORITHM PARAMETERS ---
fprintf('Setting up parameters...\n');
% Grid World Parameters
params.grid_rows = 4;
params.grid_cols = 12;
params.start_state = [params.grid_rows, 1]; % Bottom-left
params.goal_state = [params.grid_rows, params.grid_cols]; % Bottom-right
% Define the cliff area (row, col)
% The cliff is the entire bottom row, except start and goal
params.cliff_states = [];
for c = 2:(params.grid_cols - 1)
params.cliff_states = [params.cliff_states; [params.grid_rows, c]];
end
% Action Definitions (1:Up, 2:Down, 3:Left, 4:Right)
params.actions = 1:4;
params.num_actions = length(params.actions);
% Reinforcement Learning Parameters
params.num_episodes = 500;
params.alpha = 0.1; % Learning rate
params.gamma = 0.99; % Discount factor
params.epsilon = 0.1; % Epsilon for epsilon-greedy policy
% Animation/Visualization Parameters
params.show_animation = true; % Set to true to animate one episode
params.animation_episode = 499; % Which episode to animate (e.g., a late one)
params.pause_time = 0.05; % Pause between steps in animation
% --- 2. RUN Q-LEARNING ---
fprintf('Starting Q-Learning...\n');
[Q_qlearning, rewards_qlearning] = run_q_learning(params);
fprintf('Q-Learning finished.\n');
% --- 3. RUN SARSA ---
fprintf('Starting SARSA...\n');
[Q_sarsa, rewards_sarsa] = run_sarsa(params);
fprintf('SARSA finished.\n');
% --- 4. PLOT PERFORMANCE ---
fprintf('Plotting learning performance...\n');
figure('Name', 'Learning Performance');
plot(rewards_qlearning, 'b', 'LineWidth', 1.5);
hold on;
plot(rewards_sarsa, 'r', 'LineWidth', 1.5);
grid on;
xlabel('Episode');
ylabel('Total Reward per Episode');
title('Q-Learning vs. SARSA Performance on Cliff Walking');
legend('Q-Learning', 'SARSA');
ylim([-200, 0]); % Set y-axis limits to better see the difference
% --- 5. GENERATE AND ANIMATE FINAL PATHS ---
fprintf('Generating and animating final paths...\n');
% Generate greedy path from learned Q-table
final_path_q = generate_greedy_path(Q_qlearning, params);
final_path_sarsa = generate_greedy_path(Q_sarsa, params);
% Animate the final paths
animate_path(final_path_q, params, 'Q-Learning: Optimal Path');
animate_path(final_path_sarsa, params, 'SARSA: Optimal Path');
fprintf('Script finished.\n');
% =========================================================================
% ALGORITHM IMPLEMENTATIONS
% =========================================================================
function [Q, episode_rewards] = run_q_learning(params)
% Initialize Q-table with zeros
Q = zeros(params.grid_rows, params.grid_cols, params.num_actions);
episode_rewards = zeros(1, params.num_episodes);
for episode = 1:params.num_episodes
state = params.start_state;
total_reward = 0;
is_terminal = false;
% Set up animation for a specific episode if requested
if params.show_animation && episode == params.animation_episode
h_fig = initialize_grid_vis(params, 'Q-Learning Animation');
agent_marker = plot(state(2), state(1), 'bo', 'MarkerFaceColor', 'b', 'MarkerSize', 10);
end
while ~is_terminal
% Choose action using epsilon-greedy policy
action = choose_action(Q(state(1), state(2), :), params.epsilon);
% Take action, get next state and reward
[next_state, reward, is_terminal] = get_next_state(state, action, params);
total_reward = total_reward + reward;
% Q-Learning Update Rule (off-policy)
best_next_action_value = max(Q(next_state(1), next_state(2), :));
current_q = Q(state(1), state(2), action);
new_q = current_q + params.alpha * (reward + params.gamma * best_next_action_value - current_q);
Q(state(1), state(2), action) = new_q;
% Move to the next state
state = next_state;
% Update animation
if params.show_animation && episode == params.animation_episode
set(agent_marker, 'XData', state(2), 'YData', state(1));
drawnow;
pause(params.pause_time);
end
end
episode_rewards(episode) = total_reward;
% Display progress
if mod(episode, 50) == 0
fprintf('Q-Learning: Episode %d/%d, Reward: %f\n', episode, params.num_episodes, total_reward);
end
end
end
function [Q, episode_rewards] = run_sarsa(params)
% Initialize Q-table with zeros
Q = zeros(params.grid_rows, params.grid_cols, params.num_actions);
episode_rewards = zeros(1, params.num_episodes);
for episode = 1:params.num_episodes
state = params.start_state;
total_reward = 0;
is_terminal = false;
% Choose first action A from state S
action = choose_action(Q(state(1), state(2), :), params.epsilon);
% Set up animation for a specific episode if requested
if params.show_animation && episode == params.animation_episode
h_fig = initialize_grid_vis(params, 'SARSA Animation');
agent_marker = plot(state(2), state(1), 'ro', 'MarkerFaceColor', 'r', 'MarkerSize', 10);
end
while ~is_terminal
% Take action A, observe R, S'
[next_state, reward, is_terminal] = get_next_state(state, action, params);
total_reward = total_reward + reward;
% Choose next action A' from next state S'
next_action = choose_action(Q(next_state(1), next_state(2), :), params.epsilon);
% SARSA Update Rule (on-policy)
next_q = Q(next_state(1), next_state(2), next_action);
current_q = Q(state(1), state(2), action);
new_q = current_q + params.alpha * (reward + params.gamma * next_q - current_q);
Q(state(1), state(2), action) = new_q;
% Update state and action for the next iteration
state = next_state;
action = next_action;
% Update animation
if params.show_animation && episode == params.animation_episode
set(agent_marker, 'XData', state(2), 'YData', state(1));
drawnow;
pause(params.pause_time);
end
end
episode_rewards(episode) = total_reward;
% Display progress
if mod(episode, 50) == 0
fprintf('SARSA: Episode %d/%d, Reward: %f\n', episode, params.num_episodes, total_reward);
end
end
end
% =========================================================================
% HELPER FUNCTIONS
% =========================================================================
function action = choose_action(q_values, epsilon)
% Epsilon-greedy action selection
if rand() < epsilon
% Exploration: choose a random action
action = randi(length(q_values));
else
% Exploitation: choose the best action
[~, action] = max(q_values(:));
% Handle ties by choosing one randomly
best_actions = find(q_values(:) == max(q_values(:)));
action = best_actions(randi(length(best_actions)));
end
end
function [next_state, reward, is_terminal] = get_next_state(state, action, params)
% Computes the next state, reward, and terminal status
row = state(1);
col = state(2);
% Move based on action (1:Up, 2:Down, 3:Left, 4:Right)
if action == 1
row = row - 1;
elseif action == 2
row = row + 1;
elseif action == 3
col = col - 1;
elseif action == 4
col = col + 1;
end
% Check for boundary collisions and clip
row = max(1, min(params.grid_rows, row));
col = max(1, min(params.grid_cols, col));
next_state = [row, col];
% Determine reward and terminal status
reward = -1; % Default reward for a normal step
is_terminal = false;
if ismember(next_state, params.cliff_states, 'rows')
reward = -100;
next_state = params.start_state; % Fall off the cliff, reset to start
is_terminal = true; % In some formulations, this is terminal. Here we'll treat it as terminal.
elseif isequal(next_state, params.goal_state)
is_terminal = true;
end
end
function path = generate_greedy_path(Q, params)
% Generates a path from start to goal using the greedy policy from Q
state = params.start_state;
path = state;
is_terminal = false;
max_steps = params.grid_rows * params.grid_cols; % safety break
step = 0;
while ~is_terminal && step < max_steps
% Choose the best action (no exploration)
[~, action] = max(Q(state(1), state(2), :));
% Get the next state
[next_state, ~, is_terminal] = get_next_state(state, action, params);
state = next_state;
path = [path; state];
step = step + 1;
end
end
function h_fig = initialize_grid_vis(params, title_str)
% Creates the initial visualization of the grid
h_fig = figure('Name', title_str);
hold on;
% Draw grid lines
for r = 0.5:(params.grid_rows + 0.5)
plot([0.5, params.grid_cols + 0.5], [r, r], 'k');
end
for c = 0.5:(params.grid_cols + 0.5)
plot([c, c], [0.5, params.grid_rows + 0.5], 'k');
end
% Color special squares
patch([0.5 1.5 1.5 0.5], [params.grid_rows-0.5 params.grid_rows-0.5 params.grid_rows+0.5 params.grid_rows+0.5], 'g'); % Start
patch([params.grid_cols-0.5 params.grid_cols+0.5 params.grid_cols+0.5 params.grid_cols-0.5], ...
[params.grid_rows-0.5 params.grid_rows-0.5 params.grid_rows+0.5 params.grid_rows+0.5], 'y'); % Goal
% Color the cliff
for i = 1:size(params.cliff_states, 1)
c = params.cliff_states(i, 2);
patch([c-0.5 c+0.5 c+0.5 c-0.5], [params.grid_rows-0.5 params.grid_rows-0.5 params.grid_rows+0.5 params.grid_rows+0.5], [0.5 0.5 0.5]);
end
axis equal;
axis ij; % Puts (1,1) in the top-left corner
set(gca, 'XTick', 1:params.grid_cols, 'YTick', 1:params.grid_rows);
xlim([0.5, params.grid_cols + 0.5]);
ylim([0.5, params.grid_rows + 0.5]);
title(title_str);
hold off;
end
function animate_path(path, params, title_str)
% Animates a given path on the grid
h_fig = initialize_grid_vis(params, title_str);
hold on;
% Plot the full path trajectory
plot(path(:,2), path(:,1), 'c-', 'LineWidth', 2);
% Create an agent marker
agent_marker = plot(path(1,2), path(1,1), 'bo', 'MarkerFaceColor', 'b', 'MarkerSize', 12);
% Animate the agent moving along the path
for i = 1:size(path, 1)
set(agent_marker, 'XData', path(i,2), 'YData', path(i,1));
drawnow;
pause(0.2);
end
hold off;
end
How to Run and Interpret the Results
Save: Save the code as a .m file (e.g., cliff_walking_main.m).
Run: Execute the script in the MATLAB command window.
Observe the Output:
Command Window: You will see progress updates for both algorithms as they run through the episodes.
Animation Windows: Two animation windows will pop up (one after the other) showing an agent moving during a late episode of training. This gives you a feel for how the agent is behaving during learning.
Performance Plot: A plot will appear titled "Q-Learning vs. SARSA Performance".
Q-Learning (Blue): You'll notice this line is generally lower and has more sharp dips. This is because Q-learning's optimal policy is to walk along the cliff edge. During training, the epsilon-greedy exploration often causes it to step off the cliff, resulting in a large negative reward (-100).
SARSA (Red): This line will typically be higher (less negative) and more stable. SARSA is on-policy, so it learns a policy that is safe given its own exploration. It learns that being near the cliff is dangerous and finds a longer, safer path.
Final Path Animations: Two final windows will show the best paths found.
Q-Learning Path: This path will be the shortest possible route, walking directly along the top edge of the cliff. This is the truly optimal path in terms of total steps if there were no exploration.
SARSA Path: This path will be longer, taking a wide arc around the cliff. It's a "safer" but suboptimal path. This is the classic demonstration of the difference between on-policy and off-policy learning in a scenario with high-risk states.