Here is a simple implementation of A* algorithm in MATLAB:
function [path, cost] = astar(maze, start, goal, heuristic)
% Inputs:
% maze: a binary matrix where 0 represents a free cell and 1 represents
% an obstacle.
% start: a 1x2 matrix representing the starting cell.
% goal: a 1x2 matrix representing the goal cell.
% heuristic: a handle to the heuristic function.
%
% Output:
% path: a matrix where each row represents a cell on the path from start to goal.
% cost: the cost of the path.
[m, n] = size(maze);
% Create a matrix to store the cost of each cell.
cost = ones(m, n) * Inf;
cost(start(1), start(2)) = 0;
% Create a matrix to store the parent of each cell.
parent = zeros(m, n);
% Create a list to store the open cells.
openset = PriorityQueue(heuristic(start, goal));
openset.put(start, 0);
% Create a list to store the closed cells.
closedset = [];
while ~openset.isempty()
% Get the cell with the lowest score in the open set.
current = openset.get();
% Check if it is the goal cell.
if isequal(current, goal)
path = goal;
while ~isequal(path(1,:), start)
path = [parent(path(1,1), path(1,2)); path];
end
return;
end
% Move the current cell from the open set to the closed set.
closedset = [closedset; current];
% Get the neighbors of the current cell.
neighbors = get_neighbors(current, maze);
for i = 1:size(neighbors, 1)
% Get the neighbor cell.
neighbor = neighbors(i,:);
% Compute the tentative cost to the neighbor cell.
tentative_cost = cost(current(1), current(2)) + 1;
if tentative_cost < cost(neighbor(1), neighbor(2))
% Update the cost of the neighbor cell.
cost(neighbor(1), neighbor(2)) = tentative_cost;
% Set the parent of the neighbor cell to the current cell.
parent(neighbor(1), neighbor(2)) = current;
% Add the neighbor cell to the open set.
priority = tentative_cost + heuristic(neighbor, goal);
openset.put(neighbor, priority);
end
end
end
% If the goal cell is not reachable, return an empty path.
path = [];
cost = Inf;
end
function neighbors = get_neighbors(cell, maze)
[m, n] = size(maze);
% Get the indices of the neighbors of the cell.
indices = [cell(1)-1, cell(2);
cell(1)+1, cell(2);
cell(1), cell(2)-1;
cell(1), cell(2)+1];
% Keep only the neighbors that are inside the maze and not obstacles.
is_valid = indices(:,1) >= 1 & indices(:,1) <= m & ...
indices(:,2) >= 1 & indices(:,2) <= n & ...
maze(sub2ind([m, n], indices(:,1), indices(:,2))) == 0;
neighbors = indices(is_valid, :);
end
To use the function, you need to define a heuristic function that estimates the distance from a cell to the goal. For example, you can use the Euclidean distance:
Here is an example of how to use the function: