Using MATLAB (779505), страница 83
Текст из файла (страница 83)
For example, 10-by-0-by-20 is a valid size for a multidimensionalarray.19-6Multidimensional ArraysBuilding Multidimensional Arrays with the cat FunctionThe cat function is a simple way to build multidimensional arrays; itconcatenates a list of arrays along a specified dimension.B = cat(dim,A1,A2...)where A1, A2, and so on are the arrays to concatenate, and dim is the dimensionalong which to concatenate the arrays. For example, to create a new array withcatB = cat(3,[2 8; 0 5],[1 3; 7 9])B(:,:,1) =2085B(:,:,2) =1739The cat function accepts any combination of existing and new data. Inaddition, you can nest calls to cat.
The lines below, for example, create afour-dimensional array.A = cat(3,[9 2; 6 5],[7 1; 8 4])B = cat(3,[3 5; 0 1],[5 6; 2 1])D = cat(4,A,B,cat(3,[1 2; 3 4],[4 3;2 1]))cat automatically adds subscripts of 1 between dimensions, if necessary. Forexample, to create a 2-by-2-by-1-by-2 array, enterC = cat(4,[1 2; 4 5],[7 8; 3 2])In the previous case, cat inserts as many singleton dimensions as needed tocreate a four-dimensional array whose last dimension is not a singletondimension. If the dim argument had been 5, the previous statement would haveproduced a 2-by-2-by-1-by-1-by-2 array. This adds additional 1s to indexing19-719Multidimensional Arraysexpressions for the array. To access the value 8 in the four-dimensional case,useC(1,2,1,2)Singleton dimensionindexAccessing Multidimensional Array PropertiesYou can use the following MATLAB functions to get information aboutmultidimensional arrays you have created.InformationFunctionExampleArray sizesizesize(C)ans =2rowsArraydimensionsndims2columns1dim32dim4ndims(C)ans =4Arraystorage andformatwhoswhosNameSizeABCD2x2x22x2x24–D4–DBytes646464192ClassdoubledoubledoubledoublearrayarrayarrayarrayGrand total is 48 elements using 384 bytes19-8Multidimensional ArraysIndexingMany of the concepts that apply to two-dimensional matrices extend tomultidimensional arrays as well.To access a single element of a multidimensional array, use integer subscripts.Each subscript indexes a dimension–the first indexes the row dimension, thesecond indexes the column dimension, the third indexes the first pagedimension, and so on.Consider a 10-by-5-by-3 array nddata of random integers:nddata = fix(8*randn(10,5,3));To access element (3,2) on page 2 of nddata, for example, use nddata(3,2,2).You can use vectors as array subscripts.
In this case, each vector element mustbe a valid subscript, that is, within the bounds defined by the dimensions of thearray. To access elements (2,1), (2,3), and (2,4) on page 3 of nddata, usenddata(2,[1 3 4],3);The Colon and Multidimensional Array IndexingMATLAB’s colon indexing extends to multidimensional arrays.
For example, toaccess the entire third column on page 2 of nddata, use nddata(:,3,2).The colon operator is also useful for accessing other subsets of data. Forexample, nddata(2:3,2:3,1) results in a 2-by-2 array, a subset of the data onpage 1 of nddata. This matrix consists of the data in rows 2 and 3, columns 2and 3, on the first page of the array.The colon operator can appear as an array subscript on both sides of anassignment statement. For example, to create a 4-by-4 array of zerosC = zeros(4,4)Now assign a 2-by-2 subset of array nddata to the four elements in the centerof C.C(2:3,2:3) = nddata(2:3,1:2,2)Avoiding Ambiguity in Multidimensional IndexingSome assignment statements, such asA(:,:,2) = 1:1019-919Multidimensional Arraysare ambiguous because they do not provide enough information about theshape of the dimension to receive the data.
In the case above, the statementtries to assign a one-dimensional vector to a two-dimensional destination.MATLAB produces an error for such cases. To resolve the ambiguity, be sureyou provide enough information about the destination for the assigned data,and that both data and destination have the same shape. For example,A(1,:,2) = 1:10;ReshapingUnless you change its shape or size, a MATLAB array retains the dimensionsspecified at its creation.
You change array size by adding or deleting elements.You change array shape by respecifying the array’s row, column, or pagedimensions while retaining the same elements. The reshape function performsthe latter operation. For multidimensional arrays, its form isB = reshape(A,[s1 s2 s3 ...])s1, s2, and so on represent the desired size for each dimension of the reshapedmatrix. Note that a reshaped array must have the same number of elements asthe original array (that is, the product of the dimension sizes is constant).Mreshape(M, [6 5])93619819-10201365430759572884553213198201365430572936759884553213Multidimensional ArraysThe reshape function operates in a columnwise manner. It creates thereshaped matrix by taking consecutive elements down each column of theoriginal data construct.Creshape(C, [6 2])57131324579 1011 126824689111012Here are several new arrays from reshaping nddata.B = reshape(nddata,[6 25])C = reshape(nddata,[5 3 10])D = reshape(nddata,[5 3 2 5])Removing Singleton DimensionsMATLAB creates singleton dimensions if you explicitly specify them when youcreate or reshape an array, or if you perform a calculation that results in anarray dimension of one.B = repmat(5,[2 3 1 4]);size(B)ans =2314The squeeze function removes singleton dimensions from an array.C = squeeze(B);size(C)ans =23419-1119Multidimensional ArraysThe squeeze function does not affect two-dimensional arrays; row vectorsremain rows.Permuting Array DimensionsThe permute function reorders the dimensions of an array.B = permute(A,dims);dims is a vector specifying the new order for the dimensions of A, where 1corresponds to the first dimension (rows), 2 corresponds to the seconddimension (columns), 3 corresponds to pages, and so on.AB= permute(A,[2 1 3])C = permute(A,[3 2 1])A(:,:,1) =B(:,:,1) =C(:,:,1) =147258369456789B(:,:,2) =A(:,:,2) =029123573461054276931Row and columnsubscripts arereversed(page-by-pagetransposition).10253457668391Row and pagesubscripts arereversed.C(:,:,2) =42C(:,:,3) =79For a more detailed look at the permute function, consider a four-dimensionalarray A of size 5-by-4-by-3-by-2.
Rearrange the dimensions, placing the columndimension first, followed by the second page dimension, the first pagedimension, then the row dimension. The result is a 4 by 2 by 3 by 5 array.19-12Multidimensional ArraysMove dimension 2 of A tofirst subscript position of B,dimension 4 to second subscript position, and so on.B = permute(A,[2 4 3 1])Inputarray AOutputarray BDimension 1234The order of dimensions inpermute’s argument list deter-5432Dimension 12344235SizeSizemines the size and shape of theoutput array. In this example, thesecond dimension moves to thefirst position. Because the seconddimension of the original array hadsize four, the output array’s firstdimension also has size four.You can think of permute’s operation as an extension of the transposefunction, which switches the row and column dimensions of a matrix.
Forpermute, the order of the input dimension list determines the reordering of thesubscripts. In the example above, element (4,2,1,2) of A becomes element(2,2,1,4) of B, element (5,4,3,2) of A becomes element (4,2,3,5) of B, andso on.Inverse PermutationThe ipermute function is the inverse of permute. Given an input array A and avector of dimensions v, ipermute produces an array B such that permute(B,v)returns A.For example, these statements create an array E that is equal to the inputarray C.D = ipermute(C,[1 4 2 3]);E = permute(D,[1 4 2 3])You can obtain the original array after permuting it by calling ipermute withthe same vector of dimensions.19-1319Multidimensional ArraysComputing with Multidimensional ArraysMany of MATLAB’s computational and mathematical functions acceptmultidimensional arrays as arguments.
These functions operate on specificdimensions of multidimensional arrays; that is, they operate on individualelements, on vectors, or on matrices.Operating on VectorsFunctions that operate on vectors, like sum, mean, and so on, by default typicallywork on the first nonsingleton dimension of a multidimensional array. Most ofthese functions optionally let you specify a particular dimension on which tooperate. There are exceptions, however. For example, the cross function,which finds the cross product of two vectors, works on the first nonsingletondimension having length three.Note In many cases, these functions have other restrictions on the inputarguments – for example, some functions that accept multiple arrays requirethat the arrays be the same size. Refer to the online help for details onfunction arguments.Operating Element-by-ElementMATLAB functions that operate element-by-element on two-dimensionalarrays, like the trigonometric and exponential functions in the elfun directory,work in exactly the same way for multidimensional cases.















