disperse.m
Sam Hallman
code written: 26 May 2010 html written: 18 Nov 2011
Demonstration of the DISPERSE function. Oftentimes when using Matlab we find ourselves having to perform a series of repetitive assignments from some kind of array, e.g., a=A(1); b=A(2); c=A(3); . . . etc. Inevitably we ask ourselves, is there a way to do this more simply? DISPERSE is syntactic sugar for performing these kinds of tasks with a single function call.
The following examples illustrate the behavior of DISPERSE on different collection classes.
Contents
Vectors
Grab elements of vectors
foo = rand(1,4) [a b c d] = disperse(foo)
foo = 0.4094 0.3654 0.8578 0.9957 a = 0.4094 b = 0.3654 c = 0.8578 d = 0.9957
Can grab a subset if you like
v = rand(1,5) [a b c] = disperse(v([1 4 5]))
v = 0.9096 0.7282 0.6020 0.0011 0.2741 a = 0.9096 b = 0.0011 c = 0.2741
Matrices
Grab columns of a matrix
A = rand(2) [c1 c2] = disperse(A)
A = 0.3656 0.2508 0.2083 0.7516 c1 = 0.3656 0.2083 c2 = 0.2508 0.7516
Transpose if you want rows
[r1 r2] = disperse(A')
r1 = 0.3656 0.2508 r2 = 0.2083 0.7516
N-D arrays
disperse generalizes to arrays of arbitrary dimension
A = rand(5,3,4,9,7);
% pick off A(:,:,:,:,1) and A(:,:,:,:,2)
[a b] = disperse(A);
it worked:
whos A a b isequal(a, A(:,:,:,:,1)) isequal(b, A(:,:,:,:,2))
Name Size Bytes Class Attributes A 5-D 30240 double a 4-D 4320 double b 4-D 4320 double ans = 1 ans = 1
RGB images (special case)
The techniques of the previous section are especially handy for RGB images:
% Grab the R, G, and B color channels im = imread('street1.jpg'); [r g b] = disperse(im);
it worked:
whos im r g b isequal(r, im(:,:,1)) isequal(g, im(:,:,2)) isequal(b, im(:,:,3))
Name Size Bytes Class Attributes b 480x640 307200 uint8 g 480x640 307200 uint8 im 480x640x3 921600 uint8 r 480x640 307200 uint8 ans = 1 ans = 1 ans = 1
Cells
Grab elements of cells
c = { 'sam', -1, rand(5) }
[c1 c2 c3] = disperse(c)
c = 'sam' [-1] [5x5 double] c1 = sam c2 = -1 c3 = 0.2945 0.0056 0.9591 0.9123 0.1125 0.6334 0.0572 0.8658 0.1883 0.6698 0.5971 0.0029 0.2624 0.4064 0.2496 0.7556 0.5436 0.4880 0.2552 0.6699 0.6972 0.7148 0.4085 0.7605 0.3863
You can go further
c = { 'foo' {} ; [1,2;3,4] 'bar' } [a b] = disperse(c)
c = 'foo' {} [2x2 double] 'bar' a = 'foo' [2x2 double] b = {} 'bar'
Structs
Grab elements of structure arrays
s = struct('strings', {'sam','hello'}, 'lengths', [3 5]) [a b] = disperse(s)
s = 1x2 struct array with fields: strings lengths a = strings: 'sam' lengths: [3 5] b = strings: 'hello' lengths: [3 5]