|
Alan_Weiss <aweiss@mathworks.com> wrote in message <jrakm2$ncp$1@newscl01ah.mathworks.com>...
> I wonder if anyone has a nice way of automatically padding vectors (or
> matrices) with 0 so they can be concatenated.
>
> For example, suppose I have vectors
> A = [1 2 3]
> B = [3 0 4 0 5]
> C = [2 1]
>
> I would like to have a function supervertcat(A,B,C) that outputs the matrix
> [1 2 3 0 0
> 3 0 4 0 5
> 2 1 0 0 0]
>
> I would also like this to work for matrices:
> A = [1,2;...
> 3,4]
> B = [1,2,3]
> C = supervertcat(A,B) =
> [1,2,0
> 3,4,0
> 1,2,3]
>
> Does anyone have a nice way of doing this? I have seen the file exchange
> submissions PADADD, PADCAT, and CATPAD, which seem fine, but are a bit
> more heavyweight than I am seeking. I suspect there is a cute 2- or
> 3-liner out there somewhere.
>
4 lines, and not very cute, but anyway here is my proposal:
function C = supervertcat(varargin)
% C = supervertcat(A1, A2, ...)
[i j v] = cellfun(@find, varargin, 'uni',0);
r = [0 cumsum(cellfun('size',varargin,1))];
[i j v] = arrayfun(@(k) deal(r(k)+i{k}(:),j{k}(:),v{k}(:)), 1:nargin,'uni',0);
C = accumarray([cat(1,i{:}) cat(1,j{:})], cat(1,v{:}));
end
|