首页 > 代码库 > MATLAB中多个一维数组的合并

MATLAB中多个一维数组的合并

1、一维数组直接合并
       题目:
           数组work1[x1,x2——,xn],work2[y1,y2——,yn],现在要生成一个数组work3,
       work3中的数据为[x1,x2,x3--xn,y1,y2--yn];

       合并方法:
           直接将两个矩阵合并:
             A = [1,2,3,4];
             B = [-1,-2,-3,-4];
             C = zeros(1,size(B,2)+size(A,2));     %这句可以不要;
             C = [A, B];


    2、一维数组交叉合并:
       题目:
           数组work1[x1,x2——,xn],work2[y1,y2——,yn],现在要生成一个数组work3,
       work3中的数据为[x1,y1,x2,y2——,xn,yn];
      
       合并方法一:
           A = [1,2,3,4];
           B = [-1,-2,-3,-4];
           C = zeros(1,size(B,2)+size(A,2));
           C(1:2:end) = A;
           C(2:2:end) = B
          
           C =
                1    -1     2    -2     3    -3     4    -4

       解法二:
           A = [1,2,3,4];
           B = [-1,-2,-3,-4];
           C=[A‘ B‘]‘;
           C=reshape(C, 1, length(A)+length(B));
          
           C =
                1    -1     2    -2     3    -3     4    -4

 

       解法三:

           对于解法二改进:

           c=reshape([A;B],1,[]);

           这里要注意,只能在v7以上的版本才能使用此法;

 

       解法四:
           A = [1,2,3,4];
           B = [-1,-2,-3,-4];
           C=kron(A,[1 0])+kron(B,[0 1]);
          
           C =
                1    -1     2    -2     3    -3     4    -4
      很多技巧,试总结以上的方案:
          -------------------------------------
          A = [1,2,3,4];
          B = [-1,-2,-3,-4];
          ----------------- 1 -----------------
          C = zeros(1,size(B,2)+size(A,2));
          C(1:2:end) = A;
          C(2:2:end) = B;
          C=C(:);
          ------------------2 -----------------
          C=[A‘ B‘]‘;
          C=reshape(C, 1, length(A)+length(B));
          ------------------3-------------------
          c=reshape([A;B],1,[])
          ------------------4-------------------
          C=kron(A,[1 0])+kron(B,[0 1]);
          --------------------------------------