Cute Tricks in MATLAB Adapted from Other Languages
I recently saw Steve Baker's web site while searching for something. It contains some cute (Steve's word) programming tricks and I thought I would show how to do a couple of these in MATLAB.
Contents
Power of Two Test
Here's the C code:
b = ((n&(n-1))==0) ;
and now the M code:
n = 1:8 ispow2 = bitand(n,n-1) == 0
n = 1 2 3 4 5 6 7 8 ispow2 = 1 1 0 1 0 0 0 1
Swap Two Integer Values
C code to swap integers x and y x = x ^ y ; y = x ^ y ; x = x ^ y ;
x = 3 y = 17 x = bitxor(x,y) y = bitxor(x,y) x = bitxor(x,y)
x = 3 y = 17 x = 18 y = 3 x = 17
Of course, I showed how to do this more easily a while ago using an anonymous function:
swap=@(varargin)varargin{nargin:-1:1}; x = 3 y = 17 [x,y] = swap(x,y)
x = 3 y = 17 x = 17 y = 3
Force All Non-zeros to 1
The C code:
b = !!a ;
and the MATLAB code:
a = [0 1 3 0 5 7 9 0 -3 0 0]
b = +(a~=0) % use leading + to make result double instead of logical.
a = 0 1 3 0 5 7 9 0 -3 0 0 b = 0 1 1 0 1 1 1 0 1 0 0
What Byte Order is My Computer?
The C code:
int i = 1 ; little_endian = *((char *) &i ) ;
and the MATLAB code:
a = uint16(1); b = typecast(a,'uint8') little = [1 0]; % big = [0 1]; islittle = isequal(b,little)
b = 1 0 islittle = 1
or
[omit, omit, endian] = computer
omit = 2.1475e+009 omit = 2.1475e+009 endian = L
Set Different Bits
Set the least significant bit to 0. Here's the C code.
n&(n-1)
and the M code:
n = uint8(0:7) lb1 = bitset(n,1,0)
n = 0 1 2 3 4 5 6 7 lb1 = 0 0 2 2 4 4 6 6
Other Tricks?
Share your MATLAB tricks with me.
Acknowledgment
Steve Eddins, famous for many things, including his blog on image processing, just updated one of our blog publishing tools, allowing you to see the code behind most of our posts with the push of a mouse button. Pretty cool, huh! Be sure to read his recent blog article about the default MATLAB image.
- Category:
- Less Used Functionality