You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按规则动态拆分维度为8的倍数的Cell Array?

How to Split a Cell Array into Groups with 8-Step Intervals

Got it, let's break this down clearly. You have a cell array A (like 1×192) where its length is a multiple of 8, and you need to split it into 8 separate cell arrays—each grabbing elements that are 8 positions apart, starting from index 1 through 8 respectively. Here are two solid approaches to do this in MATLAB:

Approach 1: Using a Loop (Intuitive for Beginners)

This method is straightforward and easy to follow, perfect if you want to see exactly how each group is built:

% First, verify the length of A is a multiple of 8 (optional but safe)
assert(mod(length(A), 8) == 0, 'Length of A must be a multiple of 8');

num_groups = 8;
% Initialize a cell array to store all split groups (cleaner than 8 separate variables)
split_results = cell(1, num_groups);

for group_idx = 1:num_groups
    % Grab elements starting at group_idx, stepping by 8 each time
    split_results{group_idx} = A(group_idx:8:end);
end

What's happening here?

  • The index group_idx:8:end targets exactly the elements you want: for group_idx=1, it's 1, 9, 17...; for group_idx=2, it's 2, 10, 18..., and so on.
  • If you really need separate variables (like C1 to C8) instead of a single cell array, you could add eval(['C', num2str(group_idx), ' = split_results{group_idx};']) inside the loop—but avoid eval when possible; using a cell array is more maintainable.

Approach 2: Vectorized Operation (Faster & More Concise)

For larger arrays, this method is more efficient and uses MATLAB's built-in array operations to skip the loop:

% Again, verify the length first
assert(mod(length(A), 8) == 0, 'Length of A must be a multiple of 8');

% Reshape A into an 8-row array (columns hold consecutive 8 elements from original A)
reshaped_A = reshape(A, 8, []);
% Transpose and convert each row to a cell element to get your split groups
split_results = num2cell(reshaped_A', 2);

How this works:

  • reshape(A, 8, []) turns your 1×192 array into an 8×24 array (since 192 ÷ 8 = 24). Each column here has the next 8 elements from A.
  • Transposing gives us a 24×8 array, then num2cell(..., 2) converts each row into a single cell. The result is a 1×8 cell array where each element is your desired group—same output as the loop method, just faster.

Either approach will get you exactly what you need. Pick the loop if you want clarity, or the vectorized method for performance with big datasets.

内容的提问来源于stack exchange,提问作者Deepak Eevil Personified

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:30:53