how can fix this error of this code?
1 回表示 (過去 30 日間)
古いコメントを表示
names = {'1' '2' '3' '4' '5' '6' '7' '8' 'A' 'B' 'C'};
A1=[1 0 0 0 5 0 0 5 0 0 0; ...
0 1 0 0 0 0 5 5 0 0 0; ...
0 0 1 10 5 0 0 0 0 0 0;...
0 0 10 1 0 0 3 0 0 0 0;...
5 0 5 0 1 0 0 0 1 0 0; ...
0 0 0 0 0 1 0 5 0 1 0;...
0 5 0 3 0 0 1 0 0 0 1;...
5 5 0 0 0 5 0 1 0 0 0;...
0 0 0 0 1 0 0 0 1 0 0;...
0 0 0 0 0 1 0 0 0 1 0;...
0 0 0 0 0 0 1 0 0 0 1];
% Initialize variables
start_node = names == 'A'; % index of starting node
end_nodes = names == 'B' | names == 'C'; % indices of ending nodes
distances = Inf(size(names)); % initialize distances to infinity
distances(start_node) = zeros(1); % distance from start node to itself is zero
visited = false(size(names)); % initialize visited array to false
% Run Dijkstra's algorithm
while ~all(visited(end_nodes))
% Find unvisited node with smallest tentative distance
[~, current_node] = min(distances(~visited));
% Mark current node as visited
visited(current_node) = true;
% Update distances for neighbors of current node
for neighbor = find(A1(current_node,:))
if ~visited(neighbor)
new_distance = distances(current_node) + A1(current_node,neighbor);
if new_distance < distances(neighbor)
distances(neighbor) = new_distance;
end
end
end
end
% Print shortest distances to ending nodes
fprintf('Shortest distances to ending nodes:\n');
for i = find(end_nodes)
fprintf('%s: %d\n', names{i}, distances(i));
end
% Find shortest path to B and C
if distances(names == 'B') < distances(names == 'C')
shortest_path = {'A' 'B'};
else
shortest_path = {'A' 'C'};
end
% Print shortest path
fprintf('Shortest path: %s', shortest_path{1});
for i = 2:length(shortest_path)
fprintf(' -> %s', shortest_path{i});
end
fprintf('\n');
this is error
start_node = names == 'A'; % index of starting node
↑
Error: Incorrect use of '=' operator. To assign a value to a variable, use '='. To compare values for equality,
use '=='.
0 件のコメント
回答 (1 件)
Aman
2023 年 5 月 29 日
Hi there,
In the line,
start_node = names == 'A';
You are trying to use '==' operator on names which is a cell array and cell arrays do not support '==' operations. Since names only contains character data type, so you can define them using array as follow:
names = ['1' '2' '3' '4' '5' '6' '7' '8' 'A' 'B' 'C'];
Hope it helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Dijkstra algorithm についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!