Adding zeroes to Row Vector using a script
Show older comments
I wanted to create a script, which would insert "m" amount of zeroes just after every "M-th" element of a given vector, x, to create a new vector. Ie: x = [1 2 3 4 5 6] for instance.
The input would use y = zero_insertion(x,M,m)
Code so far: function y = zero_insertion(x,M,m) a = zeros(1,m) w = x(1:M) y = [w a]
and that will get me a row vector with that has up to the M-th element and the number of "m" zeroes afterwards. However, I just can't figure out how to make a loop to do that for every "M-th" element, and I also can't retrieve the rest of my original vector.
x = [1 2 3 4 5 6] for instance.
Example: If input was y = zero_insertion([1 2 3 4 5 6],1,1) then result would be [1 0 2 0 3 0 4 0 5 0 6 0]
How would I do this? Thanks for your assistance
Accepted Answer
More Answers (1)
Sean de Wolski
on 25 May 2012
x2 = zeros(1,2*numel(x)); %thanks Andrei!
x2(1:2:end) = x;
Or:
reshape([x;zeros(size(x))],1,[])
2 Comments
Andrei Bobrov
on 25 May 2012
Hi Sean! Small typo
x2 = zeros(1,2*numel(x));
x2(1:2:end) = x;
Sean de Wolski
on 25 May 2012
yup, thanks Andrei!
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!