MATLAB Answers

Rikke
0

How to extend/add elements to an array?

Asked by Rikke
on 15 Apr 2019
Latest activity Commented on by Rikke
on 17 Apr 2019
I want to extend an array at the points were the array are 0.
For example an array like this:
A=[2 3 4 5 0 1 4 5 5 0 3 4 0 2 0 ];
At each zero in A i want to extend by B=[3 2 3 5];
so the new array will be:
C=[2 3 4 5 0 0 0 1 4 5 5 0 0 3 4 0 0 0 2 0 0 0 0 0];

  0 Comments

Sign in to comment.

2 Answers

Answer by Andrei Bobrov
on 15 Apr 2019
Edited by Andrei Bobrov
on 16 Apr 2019
 Accepted Answer

A = [2 3 4 5 0 1 4 5 5 0 3 4 0 2 0 ];
B = [3 2 3 5];
out = A(sort([find(A),repelem(find(A == 0),B)]));

  4 Comments

Show 1 older comment
@Andrei
I wrote wrong in the first place, i want all the zeros to exceed so B will be for example:
B= [3 2 3 5];
out will then be =[2 3 4 5 0 0 0 1 4 5 5 0 0 3 4 0 0 0 2 0 0 0 0 0];
Hi Rikke!
I fixed my answer.
Brilliant! Thanks!

Sign in to comment.


Answer by Rikke
on 16 Apr 2019

I got the solution for B= [3 2 3 5]. Thanks Andrei!
A=[2 3 4 5 0 1 4 5 5 0 3 4 0 2 0 ];
B=[3 2 3 5];
jj = find(A == 0);
out = A(sort([find(A),jj,repelem(jj,B)]));
Madhan I think ii is if you want to add zeros to spesific zeros in the array and not all of them.

  1 Comment

Yes ;)

Sign in to comment.