%>> Usage: [arrayA] = vect2array (vectorA, dimArray)
%>> Abstract: This function returns an N-Dimensions array ("arrayA") with the same elements as "vectorA" but reshaped to have the
% dimensions "dimArray". The elements of "arrayA" are taken ROW-WISE from "vectorA". An error results if "vectorA"
% does not have the right number of elements to calculate an array with "dimArray" dimensions.
% o In:
% vectorA: The 1-by-M*N*P... vector which we wish to convert into an M-by-N-by-P-by... array
% . dimArray: The vector [M N P ...] which indicates the dimensions of the desired Array. M*N*P*... must be the same as
% o Out
% . arrayA: The objective M-by-N-by-P-by... array consisted of the elements of "vectorA".
function[arrayA] = vect2array (vectorA, dimArray)
if (nargin==0), help vect2array;return, end %help calling
if (nargin~=2), error('error 1: Incorrect number of arguments.'),end %Number of input arguments different of 2
if (length(vectorA)~= prod(dimArray)), error('error 2: "vectorA" does not have the right number of elements to calculate an array with "dimArray" dimensions'),end
%Our objective is to get a conversion Vector-to-Array taking row-wise the elements from the vector, but the built-in function 'reshape' does it taking column-wise
%the elements of the vector. This is the reason if this functin 'vect2array'. We also have to use the built-in function 'permute' to get it.
resortedDimArray=dimArray(length(dimArray):-1:1); %We change the order of elements of "dimArray" from [M N P...] to [... P N M]
%We do this to permute later to the right order of dimensions.
columnwisedArrayA=reshape(vectorA, resortedDimArray); %The vector(M*N*P...) is converted into an array(...PxNxM) by utilizasing the function 'reshape', which takes
%the elements from 'vectorA'columnwise instead rowwise.
orderOfDims=length(dimArray):-1:1; %As the "columnwisedArrayA" is an an ...by-P-by-N-by-M array insted an M-by-N-by-P-by... array, we must change the order of
%its dimensions to the right order. We defined "orderOfDims" to get this.
arrayA=permute(columnwisedArrayA, orderOfDims); % The function 'permute' rearranges the dimensions of "ArrayA" so that they are in the right order specified
% by the vector "orderOfDims".