function xout = reindex(x,y)
%REINDEX(x,y) add dimensions to make x look like y
% Assume they share some dimensions in common (as many as you like)
% Requirements: size(y) must contain all non-singleton elements in size(x)
% y cannot have two dimension of the same length
% examples:
% x = [1 2 3 4 5]; z = ones([23 5 1 6]); g = reindex(x,z);
% x = [1 2 3 4 5; 6 7 8 9 10]; z = ones([23 5 6 2 4]); g = reindex(x,z);
% g will have size of z
%
% Will Fox, 2005
% modified by Noam Katz, 7/7/06
sy0 = size(y);
sx0 = size(x);
if prod(sx0)~=prod(sy0) %if need to add non-singleton dimensions (if only singleton dim needed, see reshape below)
%remove singleton dimesnsions from x,y
x = sq(x);
sy = sy0(sy0~=1);
sx = sx0(sx0~=1);
%sort dimensions by their length
[sx,jj] = sort(sx);
[sy,kk] = sort(sy);
if size(x,2)==1 %if a vector, make it 1 x N
x = x';
elseif size(x,1)~=1
x = permute(x,jj);
end
%check that problem is well-posed
for j=1:length(sx)
if isempty(find(sy==sx(j), 1))
error('all of x dimensions must be y dimensions also (i.e. if sx = [1 80 3], sy could be [80 3 23 2] but not [80 23 2])')
end
end
for k=1:length(sy)
if sum(sy(k)==sy)>1
error('some dimensions of y have the same length, so I''m not sure how to reindex here')
end
end
%add dimensions as needed
for j = 1:length(sy)
sx(end+1:length(sy)) = 0; %pad with zeros to prevent sx(j) from giving error
if sx(j)~=sy(j)
x = shiftdim(x,j-1); %shift dimension so that new dimension should come at beginning
if size(x,1)~=1 %if not a vector
x = reshape(sq(x),[1 size(sq(x))]); %add a dimension (if it is a vector it already has a leading singleton dim (was reshaped above))
end
x = repmat(x,[sy(j) 1]); %replicate along that dimension
lsx = length(size(x));
x = shiftdim(x,lsx-(j-1)); %shift back
sx = size(x);
end
end
x = ipermute(x,kk);
%reshape to look like y (basically, add singleton dimensions if necessary)
xout = reshape(x,sy0);
else
error('sizes of x and y are equal, use permute instead')
end