Looping problem need guide.
1 view (last 30 days)
Show older comments
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
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.
Accepted Answer
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-
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!