f



"While" loop not looping

Hi there.  Here is a snippet of code that creates binary matrices and 
checks to see if they have an inverse that is also binary.  I use 
"ismember" to verify that each element in the inverse is either 0 or 1. 
  Unfortunately, the "while" loop exits immedeately.  Why?

set=[0,1];
a=round(rand(7,5));
inverse=pinv(a);
while ismember(inverse,set)~=ones(size(ismember(inverse,set)))
     a=round(rand(7,5));
     inverse=pinv(a);
     pause(0)
end
a
inverse

TIA
majb

0
bourassa-m (38)
10/22/2003 4:20:05 PM
comp.soft-sys.matlab 211264 articles. 26 followers. lunamoonmoon (257) is leader. Post Follow

1 Replies
813 Views

Similar Articles

[PageSpeed] 44

bourassa <bourassa-m@rmc.ca> writes:

> Hi there.  Here is a snippet of code that creates binary matrices and
> checks to see if they have an inverse that is also binary.  I use
> "ismember" to verify that each element in the inverse is either 0 or
> 1. Unfortunately, the "while" loop exits immedeately.  Why?
>
> set=[0,1];
> a=round(rand(7,5));
> inverse=pinv(a);
> while ismember(inverse,set)~=ones(size(ismember(inverse,set)))
>      a=round(rand(7,5));
>      inverse=pinv(a);
>      pause(0)
> end
> a
> inverse

It often helps to step through the code by hand and look at the result
of various expressions.  Run the first 3 lines, then:

ismember(inverse,set)

OK, makes sense.  Except I see some elements of 0.0000 that don't
register as 0.  More on this later.

ones(size(ismember(inverse,set)))

Nothing to see here.

ismember(inverse,set)~=ones(size(ismember(inverse,set)))

OK, notice this returns a matrix of 0's and 1's (it's also the binary
inverse of the ismember result).  What happens when you use a matrix
as a condition for a while loop?  Right, there's an implicit "all" in
there.  So you need a scalar instead.  If you use "isequal", each
element must be equal for it to return a 1.

BUT you can skip the ones() call, since you want to find the case that
ismember returns all ones.  So, use:  all(all(ismember(inverse,set)))
for the condition.


BUT notice that some elements very close to 0 and 1 will not be equal,
due to roundoff error.  You might instead want to use a tolerance,
like:

min(abs(inverse-1), abs(inverse)) < 1e-10



-- 
Peter Boettcher <boettcher@ll.mit.edu>
MIT Lincoln Laboratory
MATLAB FAQ: http://www.mit.edu/~pwb/cssm/
0
boettcher (2304)
10/22/2003 4:46:22 PM
Reply: