如何使用for循环将1维数组复制到matlab中的另一个数组

时间:2015-12-03 15:17:59

标签: matlab

我有一个512位的数据,我想将它分成16个相等的部分,每个32位。如何使用for循环在MATLAB中完成?

示例:

inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0]

我想:

 outpu1=[1,0,1,0,0] output2=[0,0,0,1,1] output3=[1,0,0,1,0]

1 个答案:

答案 0 :(得分:2)

inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0];
slices = 3; %// number of slices
slicelength = numel(inputdata)/slices;
kk=1;
for ii = 1:slices
    slicedarray(ii,:) = inputdata(kk:ii*slicelength);
    kk=ii*slicelength+1;
end

现在slicedarray将包含您的切片,每行为一个切片。您不需要像您要求的输出变量,因为dynamic variable names are bad

在MATLAB中矢量化东西更快,因此您可以使用reshape

inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0];
slices = 3;
slicelength = numel(inputdata)/slices;
slicedarray(slices,slicelength)=0; %// initialise for speed
output = reshape(inputdata,[slices slicelength]);

在这两种情况下,输出都是:

output =
     1     0     0     1     0
     0     0     0     1     1
     1     0     1     0     0

可复制以供您使用:

inputdata=rand(512,1);
slicelength = 16;
slices = numel(inputdata)/slicelength;
kk=1;
slicedarray(slices,slicelength)=0;
for ii = 1:slices
    slicedarray(ii,:) = inputdata(kk:ii*slicelength);
    kk=ii*slicelength+1;
end

output = reshape(inputdata,[slices slicelength]);