在嵌套for循环Matlab中协调单元格数组

时间:2014-05-23 16:07:10

标签: arrays matlab for-loop cell nested-loops

我在 Matlab 中工作,其中嵌套for循环用于收集数据并存储在单元格数组中,但是我想收集数据并且内部循环在相同的单元阵列根据其位置。但是,我试过但它首先给出了outter循环值索引,然后是内循环,我想在同一个单元格数组中cat。 是否可以使用矢量化技巧或其他方法来解决我的案例? A我的单元格数组,我想将A中的循环值存储到对我来说很重要的各个索引中。 我的代码:

for i=1:10
A{i}=i;
k=i;
for j=-270:90:270
if (j~=0)
A{i+k}=[j];
end
k=k+1;
end
end 

实际输出:  第1至14栏

 [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]    [9]    [10]    [-180]    [-270]    [-180]    [-270]

  Columns 15 through 26

    [-180]    [-270]    [-180]    [-270]    [-180]    [-270]    [-180]    [-90]    [180]    [90]    [180]    [270]

期望输出:

 [1]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]  [2] [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]    [3] [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]    [4] [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]    [5]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]   [6]   [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]  [7]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]   [8]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]   [9]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270]   [10]  [-270 ] [-180 ]  [-90]    [ 90]   [180]   [270] 

1 个答案:

答案 0 :(得分:0)

J = -270:90:270;
J = nonzeros(J); %// avoid zeros in J
N = numel(J);
for i = 1:10
    ii = (N+1)*(i-1)+1;
    A{ii} = i;
    for n = 1:N
        A{ii+n} = J(n);
    end
end