What am I doing wrong when returning the value from the function to my loop?

1 view (last 30 days)
I have wriiten the program in c++ and verified that it works but am struggling with the loop part when converting it to MATLAB.
In c++ I have
while (int sent = dfs(s, t, INF))
but in MATLAB I do not know how to do this? Also for computing the paths from s->t in my dfs function I have the following if statment in c++
if (int sent = dfs (i, t, min (minimum, flow_capacity))) {
// adjust the capacity
Flow[s][i] += sent;
Flow[i][s] -= sent;
return sent;
How can I do this in MATLAB in where I have tried to implement the last parts but obviously have done so incorrectly? below is all my code.
Also I am aware that MATLAB has a built in function for these sorts of problems but I need to implement my own. Sorry if its something basic and trivial Im new to MATLAB.
Thanks in advance.
function ff
clear;
%adjacency matrix representing capacities
Cap = [0, 4, 5, 0, 0, 0;
0, 0, 2, 1, 4, 0;
0, 0, 0, 0, 3, 0;
0, 0, 0, 0, 0, 2;
0, 0, 0, 2, 0, 6;
0, 0, 0, 0, 0, 0;];
% source and sink
INF=999999;
s = 1;
t = 6;
max_flow=0;
len = length(Cap);
sent = 0;
Flow =zeros([len,len]);
visited=boolean(zeros(1,len));
%sent = dfs(s,t,INF);
sent = dfs(s,t,INF);
while sent==dfs(s,t,INF);
max_flow =+sent;
visited=boolean(zeros(1,len));
end
disp('Residual graph:');
disp(Flow);
disp(['Max flow is ' num2str(max_flow)]);
%dfs
function F = dfs(s,t,minimum)
visited(s) = true;
if s==t
F = minimum;
end
for i = 1:len
flow_cap = Cap(s,i) - Flow(s,i);
if ~visited(i) && flow_cap > 0
if sent == dfs(i,t,min(minimum,flow_cap))
Flow(s,i) = Flow(s,i)+sent;
Flow(i,s) = Flow(i,s)-sent ;
F=+sent;
end
end
end
end
end

Accepted Answer

Jan
Jan on 5 Apr 2022
Edited: Jan on 5 Apr 2022
% C++:
% while (int sent = dfs(s, t, INF))
sent = dfs(s, t, INF);
while sent ~= 0
sent = dfs(s, t, Inf);
end
And:
% if (int sent = dfs (i, t, min (minimum, flow_capacity))) {
% // adjust the capacity
% Flow[s][i] += sent;
% Flow[i][s] -= sent;
% return sent;
sent = dfs(i, t, min(minimum, flow_capacity));
if sent
Flow(s,i) = Flow(s,i) + sent;
Flow(i,s) = Flow(i,s) - sent;
end
Omit the useless "clear;"
Replace
Flow =zeros([len,len]);
visited=boolean(zeros(1,len));
by
Flow = zeros(len, len);
visited = false(1, len);
  1 Comment
Ryan O Malley
Ryan O Malley on 5 Apr 2022
Thanks very much, this helped me beyond messure!
I also didnt set the value of
F=0;
at the beginning of my dfs function incase anyone is looking to this question for help.

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!