MATLAB: Dear users Can anyone guide me on how to insert zero after every fourth element in an array. I have a matrix of (15×1)…final matrix should be of dimension (20×1) with 4th,8th,16th,and 20th element as zero. Thank you.

matrix manipulation

Dear users
Can anyone guide me on how to insert zero after every fourth element in an array. I have a matrix of (15×1)…final matrix should be of dimension (20×1) with 4th,8th,16th,and 20th element as zero. Thank you.

Best Answer

>> X = 1:15
X =
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
>> reshape([reshape(X,3,5);zeros(1,5)],1,[])
ans =
1 2 3 0 4 5 6 0 7 8 9 0 10 11 12 0 13 14 15 0
Note that this only works because 15 is a multiple of 3 (1 less than the step you requested, 4). If this is not always the case then a more complicated version is required.