MATLAB Concatenate matrices with unequal dimensions

后端 未结 3 1891
梦如初夏
梦如初夏 2021-01-14 07:02

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(shor         


        
相关标签:
3条回答
  • 2021-01-14 07:20

    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;

    0 讨论(0)
  • 2021-01-14 07:34

    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
    
    0 讨论(0)
  • 2021-01-14 07:35

    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
    
    0 讨论(0)
提交回复
热议问题