Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Insert zeros into a vector

283 views
Skip to first unread message

Diego Lass

unread,
Jun 24, 2009, 7:20:17 PM6/24/09
to
Hi,
I want to insert zeros into a vector in various positions. But not necessarily every other elements. For example
A = [ 1; 3; 4 ;5 ;6;7]
A =
1
3
4
5
6
7
I want to insert at the every 3 rd positon
1
3
0
4
5
0
6
7
0
What is the most efficient way of doing this?
Thanks.
Diego


Nathan

unread,
Jun 24, 2009, 7:34:02 PM6/24/09
to

http://www.mathworks.ch/matlabcentral/newsreader/view_thread/156659

% the data
v=1:7;
w=[0,0,0];
pos=[3,6,9];
% the engine
tf=false(1,numel(v)+numel(w));
r=double(tf);
tf(pos)=true;
r(tf)=w;
r(~tf)=v;
% the result
r

Diego Lass

unread,
Jun 24, 2009, 7:41:01 PM6/24/09
to
Got it!

>> B = reshape(A, 2, 6/2)

B =

1 4 6
3 5 7

>> B = cat(1,B, sparse(1,6/2))

B =

(1,1) 1
(2,1) 3
(1,2) 4
(2,2) 5
(1,3) 6
(2,3) 7

>> B = reshape(B, [], 1 )

B =

(1,1) 1
(2,1) 3
(4,1) 4
(5,1) 5
(7,1) 6
(8,1) 7

>> full(B)

ans =

1
3
0
4
5
0
6
7
0

"Diego Lass" <dlIS...@gmail.com> wrote in message <h1ucbh$f5i$1...@fred.mathworks.com>...

0 new messages