Is there a faster way to change zeros to ones and ones to zeros?

22 views (last 30 days)
Right now for a 100x100x3 uint8 matrix, this is what I have:
for f = 1:100
for g = 1:100
for h = 1:3
if gMaster(f, g, h) == 0
gMaster(f, g, h) = 1;
elseif gMaster(f, g, h) == 1
gMaster(f, g, h) = 0;
end
end
end
end
But it takes a long time to iterate through the array. Is there a faster way to do this?

Accepted Answer

jonas
jonas on 10 Sep 2018
Edited: jonas on 10 Sep 2018
You can do
A = ~A
however it returns a logical, so if you want a uint8 you have to:
A = uint8(~A)
  1 Comment
Stephen23
Stephen23 on 10 Sep 2018
Edited: Stephen23 on 10 Sep 2018
A simple way to ensure the output has the same class as the input:
A(:) = ~A
And of course it is important to note that using negation converts all non-zero values to zero, and all zeros to one, so it is not exactly equivalent to the code shown in the question: to get the exact equivalent, you would need to add some simple indexing.

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 10 Sep 2018
Edited: James Tursa on 10 Sep 2018
Assuming you have only 0's and 1's in your array, here is another way that also keeps the class of the result as uint8:
A = 1 - A;
This seems to be faster than the other methods proposed.
  1 Comment
Stephen23
Stephen23 on 10 Sep 2018
"This seems to be faster than the other methods proposed."
Changing class twice is going to be slow, so no surprises there.

Sign in to comment.

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!