0

I have a 64-by-1 vector which contains 27 non-zero values. I want to create N copies from that vector such that each copy contains only 4 non-zero values (in that case the first 6 copies will have 4 non-zero values and the last copy will contain only 3 non-zero values) using MATLAB.

For example:

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 ];

How can this be done?

mikkola
  • 3,376
  • 1
  • 19
  • 41
Mohab Mostafa
  • 109
  • 1
  • 8
  • You need to elaborate on this question as it is not clear at all. Please give a worked example using smaller example data – Dan Nov 30 '15 at 11:11
  • 1
    See MATLAB's `find` function then take the indexes it returns 4 by 4 in order to fill your copies (that you'll previously had filled with zeros) – BillBokeey Nov 30 '15 at 11:23

1 Answers1

0

Perhaps something like:

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);
Matthew Gunn
  • 4,451
  • 1
  • 12
  • 30