Insert zeros in random positions following another zero
Show older comments
Hi All,
I have a large array such as this one: X = [2 1 0 4 5 0 778 90 0 3 88 0 77 66 0 12 23 0 45 80 0 89 67 0 34 67 0 76 32 0]; (just much larger)
I'd like to insert 20% of additional zeros at random positions following another 0 such as:
new_X = [2 1 0 0 4 5 0 778 90 0 3 88 0 77 66 0 12 23 0 0 45 80 0 89 67 0 34 67 0 76 32 0];
I need to find the indeces of the zeros in X but then I can't get the "random" 20% of zeros correct...
Does anybody know how to do that?
Kind regards
Phil
Accepted Answer
More Answers (1)
Davide Masiello
on 28 Nov 2023
Edited: Davide Masiello
on 28 Nov 2023
This should work without the need for a for loop.
X = [2 1 0 4 5 0 778 90 0 3 88 0 77 66 0 12 23 0 45 80 0 89 67 0 34 67 0 76 32 0];
Select two random locations and increase the index by one (i.e. the new zero goes after the old random zero).
idx = sort(randsample(find(X==0),2));
idx = idx+[1:length(idx)]
Create a new vector of NaNs of the length required for the new vector.
newX = nan(1,length(X)+length(idx));
First place the new additional zeros.
newX(idx) = 0;
Then add the old vector where the NaNs are left.
newX(isnan(newX)) = X;
See the result below
disp(newX)
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!