how to write such a loop?
2 ビュー (過去 30 日間)
古いコメントを表示
hello,
if i have a n*1 vector. every element can interact with each other.an 1 at position (i,j) means member i will change its state with member j.an zero means they do not change together. so all the interactions between any two elements can be expressed in a n*n matrix (diagnal is 0 means i^th element do not interact with itself):
0 1 0 1 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
now my question is: i want to begin with a random place, and find all that co-change with it (all the friends), then go on and find all that co-change with its friends (new friends), and go on until no new friends can be find.
eg.
1. i begin with element 1.
2. i go to first row, find element 2 and 4 are friends
3. then i go to row2 find 1 (not new friends); go to row 4 find 1 (again) and 5 (new friends);
4. then continue to row 5, find 4 (not new friends) 5. mark 1,2,4,5 as friends. 6. go back to step 1, find a new element (other than 1,2,4,5) to start with.
i have some bigger matrix to work with (100*100)...and this has been puzzled me for a while, please help me out.
thanks a lot.
Shuoguo
回答 (3 件)
the cyclist
2011 年 4 月 12 日
Here is a solid kick in the right direction. The while-loop only tests if you have found all possible friends (based on the size of the original array). It does not test whether you have reached a "steady-state" because the network does not extend to all possible people. Should be easy to add that, if you want.
A = [0 1 0 1 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
1 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0];
N = size(A,1); % Assume symmetric, square array A
allFriends = 1:N;
oldFriends = 1
pause(1)
while not(numel(oldFriends)==numel(allFriends))
for nf = oldFriends
newFriends = find(A(nf,:));
oldFriends = union(oldFriends,newFriends); % Automatically sorted by MATLAB, which is important for while test.
end
oldFriends
pause(1)
end
Walter Roberson
2011 年 4 月 12 日
I didn't catch the bit about the spin variable, but the other part sound like standard matrix traversal that is implemented by taking successive matrix powers.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Discrete Math についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!