Looping problem need guide.

6 views (last 30 days)
reez all
reez all on 24 Feb 2012
Edited: Cedric on 23 Oct 2013
how to use loop that the number of edges for output is equal as the input for the coding below:
clear;
clc;
nodes=6;
edges=8;
cnt = 0;
DG = zeros(nodes);
ancs = zeros(nodes); % matrix of ancestors
childs = zeros(nodes); % matrix of children
for e=1:edges
i=randi(nodes-1,1); % source node for new edge
j=randi([i+1,nodes],1); % target node for new edge
if sum(sum(DG(logical(ancs(j,:)),logical(childs(i,:)))))==0 && ...
sum(sum(DG(logical(ancs(i,:)),logical(childs(j,:)))))==0 && ...
sum(DG(logical(ancs(i,:)),j))==0 && sum(DG(i,logical(childs(j,:))))==0
% add edge
DG(i,j)=1;
% update ancestor and children relationship in the graph
ancs(j,i)=1;
ancs(j,:)=ancs(j,:)|ancs(i,:);
childs(i,j)=1;
childs(i,:)=childs(i,:)|childs(j,:);
end
end
edge=sum(sum(DG));
disp(edge);
i try to use while loop but still not work correctly. thank you.
  2 Comments
Jan
Jan on 24 Feb 2012
@Reez all: Please do not send me emails. I answer every question I can answer. Trying to push me by emails does decrease my motivation to even read a question. Thanks.
It you really think that contacting the contributors directly is helpful, be sure to add a link to the question in your mail.
reez all
reez all on 24 Feb 2012
I apologise. I'm just think that you can help me because i see that you have wide knowledge related to the matlab. Sorry for interrupting you.

Sign in to comment.

Accepted Answer

Geoff
Geoff on 24 Feb 2012
So you mean that you want the number of 1's in DG to be equal to edges?
I would say that if-condition is preventing some edges from being added, and you are assuming by looping from 1:edges that it will be satisfied every time. Your two calls to randi do not guarantee that the same edge has not already been added. You say you used a while-loop... Was it similar to the following?
while sum(DG(:)) < edges
....
end
That would guarantee the end-result that you seem to be looking for. If the loop never terminates, then there is bound to be a problem with the logic in the if, which looks more convoluted than perhaps it needs to be.
-g-
  1 Comment
reez all
reez all on 24 Feb 2012
thank you for your help, yes i need the number of 1's in DG to be equal to edges. i also have use the while loop that similar with the following code and as result the loop never terminates.
do you have any suggestion to improve my 'if' condition so that it can generate the same result?? The 'if' condition is full fill the Partially ordered set which is the main objective of my code. im really appreciate if you can help me to repair this code.

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!