0% found this document useful (0 votes)
6 views

CODE-BTL

The document contains a MATLAB function for implementing the A* algorithm on a dynamically constructed graph with partial connectivity. Users can input node coordinates, which are connected based on a distance threshold, and the algorithm finds the shortest path between a specified start and goal node while visualizing the process. The function also displays a cost table for each node after the pathfinding is complete.

Uploaded by

thinh109.206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CODE-BTL

The document contains a MATLAB function for implementing the A* algorithm on a dynamically constructed graph with partial connectivity. Users can input node coordinates, which are connected based on a distance threshold, and the algorithm finds the shortest path between a specified start and goal node while visualizing the process. The function also displays a cost table for each node after the pathfinding is complete.

Uploaded by

thinh109.206
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

CODE

function dynamic_a_star_with_partial_connectivity()
% Initialize variables
nodes = {}; % Node labels
positions = []; % Node coordinates
edges = []; % Edges (from-to pairs)
weights = []; % Corresponding weights
node_count = 0;

% Visualization setup
figure;
hold on;
axis equal;
grid on;
title('Dynamic Graph Visualization with A* Algorithm');
xlabel('X');
ylabel('Y');

% Input nodes dynamically


disp('Enter node coordinates as x,y. Type "." to stop input:');
while true
user_input = input('Enter coordinate (x,y or "."): ', 's');
if strcmp(user_input, '.')
break; % Stop input
end

% Parse input
coords = sscanf(user_input, '%f,%f');
if length(coords) ~= 2
disp('Invalid input. Please enter coordinates as x,y.');
continue;
end

% Add node
node_count = node_count + 1;
nodes{node_count} = sprintf('%c', 'A' + node_count - 1); % Node label
positions = [positions; coords']; % Add coordinates

% Plot the new node


plot(coords(1), coords(2), 'ko', 'MarkerSize', 8, 'MarkerFaceColor', 'y');
text(coords(1) + 0.2, coords(2), nodes{node_count}, 'FontSize', 10);

% Connect to nearby nodes


for i = 1:node_count - 1
% Calculate Euclidean distance
distance = norm(positions(node_count, :) - positions(i, :));

% Set a threshold for connectivity (e.g., 5 units)


if distance <= 5
edges = [edges, [i; node_count]]; % Add edge
random_weight = randi([1, 20]); % Generate random weight
weights = [weights, random_weight];

% Draw the new edge


line([positions(i, 1), positions(node_count, 1)], ...
[positions(i, 2), positions(node_count, 2)], ...
CODE

'Color', 'b', 'LineWidth', 1);


% Display the weight
mid_x = mean([positions(i, 1), positions(node_count, 1)]);
mid_y = mean([positions(i, 2), positions(node_count, 2)]);
text(mid_x, mid_y, sprintf('%.1f', random_weight), 'Color', 'r');
end
end
end

% Finalize node and edge input


disp('Graph construction complete.');
disp('Nodes:');
disp(nodes);

% Ask user for start and goal nodes


start_node_label = input('Enter the start node label (e.g., A): ', 's');
goal_node_label = input('Enter the goal node label (e.g., Z): ', 's');
start_index = find(strcmp(nodes, start_node_label));
goal_index = find(strcmp(nodes, goal_node_label));

if isempty(start_index) || isempty(goal_index)
error('Invalid start or goal node.');
end

% Initialize A* variables
num_nodes = length(nodes);
open_list = [start_index];
closed_list = [];
g_costs = inf(1, num_nodes); % Actual cost from start
g_costs(start_index) = 0;
f_costs = inf(1, num_nodes); % Total cost (g + h)
f_costs(start_index) = heuristic_distance(positions(start_index, :), positions(goal_index, :));
predecessors = zeros(1, num_nodes); % To trace the path

% Perform A* algorithm
while ~isempty(open_list)
% Find the node in the open list with the smallest f_cost
[~, current_idx] = min(f_costs(open_list));
current_node = open_list(current_idx);
open_list(current_idx) = []; % Remove from open list
closed_list = [closed_list, current_node]; % Add to closed list

% Stop if the goal is reached


if current_node == goal_index
break;
end

% Explore neighbors
for i = 1:size(edges, 2)
% Check if there's an edge from the current node
if edges(1, i) == current_node
neighbor = edges(2, i);
elseif edges(2, i) == current_node
neighbor = edges(1, i);
else
CODE

continue;
end

% Skip if neighbor is in the closed list


if ismember(neighbor, closed_list)
continue;
end

% Calculate tentative g_cost


edge_weight = weights(i);
tentative_g_cost = g_costs(current_node) + edge_weight;

if tentative_g_cost < g_costs(neighbor)


% Update g_cost, f_cost, and predecessor
g_costs(neighbor) = tentative_g_cost;
f_costs(neighbor) = g_costs(neighbor) + heuristic_distance(positions(neighbor, :),
positions(goal_index, :));
predecessors(neighbor) = current_node;

% Add to open list if not already there


if ~ismember(neighbor, open_list)
open_list = [open_list, neighbor];
end
end
end

% Update visualization: highlight the current node


highlight_node(positions, current_node, 'c');
pause(0.5); % Pause for visualization
end

% Traceback and highlight the shortest path


path = goal_index;
while predecessors(path(1)) > 0
path = [predecessors(path(1)), path];
end

% Highlight the shortest path in green


for i = 1:length(path) - 1
pt1 = positions(path(i), :);
pt2 = positions(path(i+1), :);
line([pt1(1), pt2(1)], [pt1(2), pt2(2)], 'Color', 'g', 'LineWidth', 2);
end
disp('Shortest path highlighted in green.');

% Display the cost table


node_table = table(nodes', g_costs', f_costs', predecessors', ...
'VariableNames', {'Node', 'g_Cost', 'f_Cost', 'Previous_Node'});
disp(node_table);
end

function h = heuristic_distance(point1, point2)


% Calculate Euclidean distance (heuristic)
h = norm(point1 - point2);
end
CODE

function highlight_node(positions, node_idx, color)


% Highlight a specific node
plot(positions(node_idx, 1), positions(node_idx, 2), 'o', ...
'MarkerSize', 10, 'MarkerFaceColor', color, 'MarkerEdgeColor', 'k');
end

You might also like