Adding zeroes to Row Vector using a script

조회 수: 1 (최근 30일)
Ben
Ben 2012년 5월 25일
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

채택된 답변

Nathaniel
Nathaniel 2012년 5월 25일
It would be simple if you guaranteed that numel(x)/M is always an integer, but without that guarantee:
function y = zero_insertion(x,M,m)
modxm = mod(numel(x),M);
padding = logical(modxm)*M-modxm;
newx = reshape([x NaN(1,padding)],M,[]);
y1 = [newx ; zeros(m, size(newx,2))];
y2 = reshape(y1,1,[]);
y = y2(1:(numel(y2)-logical(padding)*(padding+m)));
Or if you want to keep the zeros even if numel(x)/M isn't an integer, the last line is:
y = y2(~isnan(y2));
  댓글 수: 1
Ben
Ben 2012년 5월 27일
Thanks so much! This is exactly what I needed to create.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2012년 5월 25일
x2 = zeros(1,2*numel(x)); %thanks Andrei!
x2(1:2:end) = x;
Or:
reshape([x;zeros(size(x))],1,[])
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2012년 5월 25일
Hi Sean! Small typo
x2 = zeros(1,2*numel(x));
x2(1:2:end) = x;
Sean de Wolski
Sean de Wolski 2012년 5월 25일
yup, thanks Andrei!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by