Andrea Perissinotto
Andrea Perissinotto

Reputation: 184

Inserting selected number of zeros between fixed number of non-zero elements in a vector in MATLAB

I have a vector like A=[1,2,3,4,5,6,7,8,9,10]; I would like to insert 2 zero every 5 number.
The result would be A=[1,2,3,4,5,0,0,6,7,8,9,10,0,0].

I know I could preallocate the space and then use a for cycle to assign the variable, but I was wandering if there was some more elegant way.

Upvotes: 3

Views: 128

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112699

This works even if A doesn't contain an integer number of blocks:

A = [1,2,3,4,5,6,7,8,9,10,11,12]; % input vector
m = 5; % block size
n = 2; % number of zeros to be added after each block
B = zeros(1, numel(A)+floor(numel(A)/m)*n); % preallocate to appropriate size
B(mod(0:end-1, m+n)<m) = A; % logical index. Fill values of A at desired positions of B

The result in this example is

B =
     1   2   3   4   5   0   0   6   7   8   9  10   0   0  11  12

Upvotes: 4

Divakar
Divakar

Reputation: 221584

With A having number of elements a multiple of 5, you could use some reshaping and concatenation with zeros, like so -

reshape([reshape(A,5,[]) ; zeros(2,numel(A)/5)],1,[])

Upvotes: 1

Related Questions