简体   繁体   中英

why does the code stuck in the while loop even though i try to break on the loop?(matlab)

The code

ite = 5 ;
cell = 5;
MRJIT = xlsread('5 Node.xlsm',1,'L62: P67');
max_col = 5 ;

for m=1:ite
    for n=1:max_col 
       a = randi(cell)
       b = randi(cell)
        while (eq(a,b) ||(MRJIT(a,n)==0 && MRJIT(b,n)==0)) 
            if (a~=b)&&(MRJIT(a,n)> 0 || MRJIT(b,n)>0)
                break;
            end
            a = randi(cell)
            b = randi(cell)

        end
        MRJIT([a,n b,n]) = MRJIT([b,n a,n]) %swap value
    end
end

Code explanation

there are 5 column on this table, 5 node.xls the point of this code is to swap values between 2 cell on each column from the table above that are selected by choosing 2 random number that is a and b but only if one of the selected cell value is not zero, if both of the cell values equal to zero, it will need to select another 2 random number until the one of the selected cells values is not equal to zero

The Question

1.why does the code stuck in the while loop? when i try to force stop the program, it shows some of the a and b values are not the same or equal to zero, but it kept stuck on the while loop

  1. Why does the program only run on column 1 and not the others?

This statement

MRJIT([a,n b,n]) = MRJIT([b,n a,n])

does not swap two values. [a,nb,n] is the same as [a,n,b,n] . That is, you are addressing three values using linear indexing (one of them twice). Alternatives: use sub2ind to compute linear indices to your two values, so you can swap them in one statement like you tried, or use a temporary variable to store the one value, and swap them indexing one item at the time. There is no direct way in MATLAB to index two elements in one operation, unless the elements are on the same row or column (except using linear indices, of course).

Using the sub2ind alternative, you could write:

a = sub2ind(a,n);
b = sub2ind(b,n)
MRJIT([a,b]) = MRJIT([b,a]);

Note the difference between MRJIT([a,b]) and MRJIT(a,b) .

The other alternative is:

tmp = MRJIT(a,n);
MRJIT(a,n) = MRJIT(b,n);
MRJIT(b,n) = tmp;

--

As an aside, you might be able to improve (speed up) the way you find a and b by (not tested):

a = 0;
while(MRJIT(a,n)==0)
   a = randi(cell);
end
b = 0;
while (a==b || MRJIT(b,n)==0)
   b = randi(cell);
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM