Invalid expression. When calling a function or indexing a variable

6 views (last 30 days)
My base data is the following one (matrix):
I'm doing a Dijkstra's Algorithm - Matlab Formulation. But when I run the code, it appears this error:
I don't know why, I found this code on the internet but I don't know how to organice it. And it's worth mentioning that it has to read the data from a file.
%---------------------------------------------------
% Dijkstra Algorithm
% author : Dimas Aryo
% email : mr.dimasaryo@gmail.com
%
% usage
% [cost rute] = dijkstra(Graph, source, destination)
%
% example
% G = [0 3 9 0 0 0 0;
% 0 0 0 7 1 0 0;
% 0 2 0 7 0 0 0;
% 0 0 0 0 0 2 8;
% 0 0 4 5 0 9 0;
% 0 0 0 0 0 0 4;
% 0 0 0 0 0 0 0;
% ];
% [e L] = dijkstra(G,1,7)
%---------------------------------------------------
datos = load('map.xlsx');
function [e L] = dijkstra(datos,1,12)
if s==d
e=0;
L=[s];
else
A = setupgraph(A,inf,1);
if d==1
d=s;
end
A=exchangenode(A,1,s);
lengthA=size(A,1);
W=zeros(lengthA);
for i=2 : lengthA
W(1,i)=i;
W(2,i)=A(1,i);
end
for i=1 : lengthA
D(i,1)=A(1,i);
D(i,2)=i;
end
D2=D(2:length(D),:);
L=2;
while L<=(size(W,1)-1)
L=L+1;
D2=sortrows(D2,1);
k=D2(1,2);
W(L,1)=k;
D2(1,:)=[];
for i=1 : size(D2,1)
if D(D2(i,2),1)>(D(k,1)+A(k,D2(i,2)))
D(D2(i,2),1) = D(k,1)+A(k,D2(i,2));
D2(i,1) = D(D2(i,2),1);
end
end
for i=2 : length(A)
W(L,i)=D(i,1);
end
end
if d==s
L=[1];
else
L=[d];
end
e=W(size(W,1),d);
L = listdijkstra(L,W,s,d);
end
function G = exchangenode(G,a,b)
%Exchange element at column a with element at column b;
buffer=G(:,a);
G(:,a)=G(:,b);
G(:,b)=buffer;
%Exchange element at row a with element at row b;
buffer=G(a,:);
G(a,:)=G(b,:);
G(b,:)=buffer;
function L = listdijkstra(L,W,s,d)
index=size(W,1);
while index>0
if W(2,d)==W(size(W,1),d)
L=[L s];
index=0;
else
index2=size(W,1);
while index2>0
if W(index2,d)<W(index2-1,d)
L=[L W(index2,1)];
L=listdijkstra(L,W,s,W(index2,1));
index2=0;
else
index2=index2-1;
end
index=0;
end
end
end
function G = setupgraph(G,b,s)
if s==1
for i=1 : size(G,1)
for j=1 :size(G,1)
if G(i,j)==0
G(i,j)=b;
end
end
end
end
if s==2
for i=1 : size(G,1)
for j=1 : size(G,1)
if G(i,j)==b
G(i,j)=0;
end
end
end
end
  2 Comments

Sign in to comment.

Answers (1)

Jan
Jan on 13 Nov 2021
You cannot use constants in the definition of the inputs of a function:
function [e L] = dijkstra(datos,1,12)
% ^ ^^
Use the original code:
function [e L] = dijkstra(A,s,d)
Do not modify the function, but define the inputs you need in another script or function:
datos = load('map.xlsx');
[e, L] = dijkstra(datos, 1, 12);
  3 Comments

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!