3

Is there any easy way to concatenate matrices with unequal dimensions using zero padding?

short = [1 2 3]';
long = [4 5 6 7]';
desiredResult = horzcat(short, long);

I would like something like:

desiredResult = 
1 4 
2 5
3 6
0 7
SCFrench
  • 8,244
  • 2
  • 31
  • 61
Jonathan Baran
  • 291
  • 1
  • 4
  • 15

3 Answers3

5

Matrices in MATLAB are automatically grown and padded with zeroes when you assign to indices outside the current bounds of the matrix. For example:

>> short = [1 2 3]';
>> long = [4 5 6 7]';
>> desiredResult(1:numel(short),1) = short;  %# Add short to column 1
>> desiredResult(1:numel(long),2) = long;    %# Add long to column 2
>> desiredResult

desiredResult =

     1     4
     2     5
     3     6
     0     7
gnovice
  • 125,304
  • 15
  • 256
  • 359
1

Matlab automatically does padding when writing to a non-existent element of a matrix. Therefore, another very simple way of doing this is the following:

short=[1;2;3];

long=[4;5;6;7];

short(1:length(long),2)=long;

Community
  • 1
  • 1
elachell
  • 2,527
  • 1
  • 26
  • 25
1

EDIT:

I have edited my earlier solution so that you won't have to supply a maxLength parameter to the function. The function calculates it before doing the padding.

function out=joinUnevenVectors(varargin)
%#Horizontally catenate multiple column vectors by appending zeros 
%#at the ends of the shorter vectors
%#
%#SYNTAX: out = joinUnevenVectors(vec1, vec2, ... , vecN)

    maxLength=max(cellfun(@numel,varargin));
    out=cell2mat(cellfun(@(x)cat(1,x,zeros(maxLength-length(x),1)),varargin,'UniformOutput',false));

The convenience of having it as a function is that you can easily join multiple uneven vectors in a single line as joinUnevenVectors(vec1,vec2,vec3,vec4) and so on, without having to manually enter it in each line.

EXAMPLE:

short = [1 2 3]';
long = [4 5 6 7]';
joinUnevenVectors(short,long)

ans =

     1     4
     2     5
     3     6
     0     7
Community
  • 1
  • 1
abcd
  • 41,765
  • 7
  • 81
  • 98
  • Would work, but was looking for a function that would not force the usage of the maxLength param. – Jonathan Baran Jun 02 '11 at 05:32
  • 1
    @Jonathan: the `maxLength` can be included inside the function so that you don't have to calculate it. I've used that in [this](http://stackoverflow.com/questions/6210495/how-to-combine-vectors-of-different-length-in-a-cell-array-into-matrix-in-matlab/6210539#6210539) answer. So just include `maxLength=max(cell2mat(cellfun(@(x)numel(x),vectors,'UniformOutput',false)));` inside the function and don't enter it as the last argument. A function is simpler, as joining multiple vectors becomes a one line command as `joinUnevenVectors(a,b,c,d,e)`, instead of manually entering it on separate lines – abcd Jun 02 '11 at 05:39