根据向量中非零值的数量创建向量的 N 个副本

Create N copies of a vector based on number of nonzero values in that vector

我有一个包含 27 个非零值的 64×1 向量。我想从该向量创建 N 个副本,使每个副本仅包含 4 个非零值(在这种情况下,前 6 个副本将具有 4 个非零值,最后一个副本将仅包含 3 个非零值值)使用 MATLAB。

例如:

orig_vector = [0 0 0 0 1 0 0 0 0 5 0 0 0 2 0 1 0 2 3 1 1 ];
first_copy  = [0 0 0 0 1 0 0 0 0 5 0 0 0 2 0 1 0 0 0 0 0 ];
second_copy = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 1 1 ];

如何做到这一点?

可能是这样的:

non_zero_indices = find(orig_vector); % get array indices of non-zero elements
n_non_zero = length(non_zero_indices);
n_copies   = ceil(n_non_zero / 4);       % eg. with 6 non-zero elements we will have 2 copies
new_vectors = zeros(n_copies, length(orig_vector));   % matrix of new vectors where vectors go in rows

for i=0:n_copies - 2
  idx = non_zero_indices(1+i*4:4+i*4);
  new_vectors(i+1, idx) = orig_vector(idx);
end
idx = non_zero_indices(1+(n_copies-1)*4:end);  % handle end which may have fewer than 4 elements
new_vectors(n_copies, idx) = orig_vector(idx);