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!