MATLAB:拆分数组

时间:2015-05-20 23:56:16

标签: matlab matrix

我有一个Matlab数组

K=[2, 4, 5, 7, 7.3, 8, 9, 0, 2.1, 5, 7, 3] % 1x12

我需要将其拆分为三个数组

[K1, K2, K3] = K

哪里

K1= 1 x 2
K2= 1 x 4
K3= 1 x 6

是否有任何单个内联命令执行此类拆分?

[K1,K2,K3]=split(K,2,4,6)

3 个答案:

答案 0 :(得分:3)

你可以写一个(我使用splitmat来避免重载split):

function varargout = splitmat(K,varargin)
nextpos = 1;
for argnum = 1:nargin-1
    varargout{argnum} = K(nextpos:nextpos+varargin{argnum}-1);
    nextpos = nextpos + varargin{argnum};
end

给出输出:

>> [K1,K2,K3]=splitmat(K,2,4,6)
K1 =
     2     4
K2 =
    5.0000    7.0000    7.3000    8.0000
K3 =
    9.0000         0    2.1000    5.0000    7.0000    3.0000

答案 1 :(得分:3)

这可能是一个更好的选择,因为您不需要创建任何单独的功能,也不必像其他答案一样手动拆分它。它还具有仅创建单个变量(单元格数组)而不是变量列表的优势。

使用mat2cell

out = mat2cell(K,1,splitvec)

<强>输入

K = [2, 4, 5, 7, 7.3, 8, 9, 0, 2.1, 5, 7, 3];
splitvec = [2 4 6];

<强>结果:

>> celldisp(out)

out{1} =

 2     4

out{2} =

5.0000    7.0000    7.3000    8.0000

out{3} =

9.0000         0    2.1000    5.0000    7.0000    3.0000

答案 2 :(得分:1)

是的,请使用deal

p1 = 2;
p2 = 4;
[K1, K2, K3] = deal(K(1:p1),K(p1+1:p1+p2),K(p1+p2+1:end))