Array2Matrix - Transform an N-dimensional array into a matrix. Each line in the output matrix lists the subscripts for all dimensions (one per column) and the corresponding value in the array. USAGE M = Array2Matrix(A) A N-dimensional array
0001 function M = Array2Matrix(A) 0002 0003 %Array2Matrix - Transform an N-dimensional array into a matrix. 0004 % 0005 % Each line in the output matrix lists the subscripts for all dimensions 0006 % (one per column) and the corresponding value in the array. 0007 % 0008 % USAGE 0009 % 0010 % M = Array2Matrix(A) 0011 % 0012 % A N-dimensional array 0013 0014 % Copyright (C) 2009-2011 by Michaƫl Zugaro 0015 % 0016 % This program is free software; you can redistribute it and/or modify 0017 % it under the terms of the GNU General Public License as published by 0018 % the Free Software Foundation; either version 3 of the License, or 0019 % (at your option) any later version. 0020 0021 % A(:,:,1,1) = [1 2 3 4 5;6 7 8 9 0]; 0022 % A(:,:,2,1) = [0 9 8 7 6;5 4 3 2 1]; 0023 % A(:,:,1,2) = [4 4 4 4 4;5 5 5 5 5]; 0024 % A(:,:,2,2) = [6 6 6 6 6;7 7 7 7 7]; 0025 % A(:,:,1,3) = [8 8 8 8 8;9 9 9 9 9]; 0026 % A(:,:,2,3) = [0 0 0 0 0;6 5 6 5 6]; 0027 0028 if nargin < 1, 0029 error('Incorrect number of parameters (type ''help <a href="matlab:help Array">Array</a>2Matrix'' for details).'); 0030 end 0031 0032 d = length(size(A)); 0033 0034 % Make a string of variable names to hold subscripts 0035 % e.g. for three dimensions: 'v1,v2,v3' 0036 subscripts = ''; 0037 for i = 1:d, 0038 subscripts = [subscripts 'v' int2str(i) ',']; 0039 end 0040 subscripts = [subscripts(1:end-1)]; 0041 0042 % Make strings to transform indices to subscripts, and to create output matrix 0043 % e.g. for three dimensions: '[v1,v2,v3]=ind2sub(size(A),(1:length(A(:)))');' 0044 % and: 'M=[v1,v2,v3 A(:)];' 0045 getSubscripts = ['[' subscripts ']=ind2sub(size(A),(1:length(A(:)))'');']; 0046 setSubscripts = ['M=[' subscripts ' A(:)];']; 0047 0048 % Evaluate those strings 0049 eval(getSubscripts); 0050 eval(setSubscripts);