MATLAB Uneven Concatenate Matrices

Is there any easy way to concatenate unevenly sized matrices 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
+2
source share
3 answers

Matrices in MATLAB automatically grow and padded with zeros when you assign indexes outside the current boundaries of the matrix. For instance:

>> 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
+4
source

EDIT:

I edited my earlier solution so that you do not have to specify a parameter maxLengthfor the function. The function calculates it before performing the fill.

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));

, joinUnevenVectors(vec1,vec2,vec3,vec4) .., .

:

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

ans =

     1     4
     2     5
     3     6
     0     7
+1

Matlab automatically indents when writing to a nonexistent matrix element. Therefore, another very simple way to do this:

short = [1, 2, 3];

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

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

+1
source

All Articles