How to insert zeros in matrix randomly?

I have this matrix:
A =
[2, 1, 4, 6, 2;
9, 4, 6, 1, 2;
5, 3, 2, 8, 3;
7, 2, 1, 9, 3;
7, 1, 8, 2, 4]
I try to insert zeros in each row so the matrix should looks like this:
A=[2, 0, 1, 4, 6, 0, 2;
9, 4, 0, 6, 0, 1, 2;
5, 3, 2, 0, 8, 0, 3;
7, 0, 2, 1, 0, 9, 3;
7, 1, 8, 0, 2, 0, 4]
In this case zeros should be inserted in between maximum of 4 digits for all rows. Any idea on how to do it?

2 Comments

In this case zeros should be inserted in between maximum of 4 digits for all rows...
What do you mean by that?
I mean that zeros should be inserted between only 1 or 2 or 3 or 4 digits for each row as maximum because later I will work on larger matrix.

Sign in to comment.

 Accepted Answer

A = [2, 1, 4, 6, 2;
9, 4, 6, 1, 2;
5, 3, 2, 8, 3;
7, 2, 1, 9, 3;
7, 1, 8, 2, 4]
zerospercol = randi(4); %up to 4 zeros per column
B = [A, zeros(size(A, 1), zerospercol)]; %append zeros
for row = 1:size(B, 1)
B(row, randperm(size(B, 2))) = B(row, :); %shuffle the row
end
B %display result

5 Comments

Thank you Guillaume, I checked the result but some of rows has zeros in sequence (one followed by another zero directly),which is not allowed in my case.
some of rows has zeros in sequence, which is not allowed in my case
That complicates things a bit:
zerosperrow = randi(4); %up to 4 zeros per row
B = zeros(size(A, 1), size(A, 2) + zerosperrow);
for row = 1:size(B, 1)
Brow = nan(1, size(A, 2)*2 + 1); %creates a row of nan double the size of the row
Brow(2:2:end) = A(row, :); %fill even indices with original row
Brow(randperm(size(A, 2)+1, zerosperrow)*2-1) = 0; %fill some odd indices with 0
B(row, :) = Brow(~isnan(Brow)); %get rid of the nans. because of the even/odd filling you're guaranteed that no two zeros are adjacent
end
Thank you very much Guillaume, it works now but can you please make the code works for large size matrix, because when changing the size for larger I got error message.
The code has no restriction on the size of the matrix (other than your computer memory). I've just tried with a 20000 x 1000 matrix and 200 zeros to insert in each row with no problem.
The only reason I could see for the code to error is if you try to put more zeros per row that could possibly fit (i.e. zerosperrow is greater than size(A, 2)+1).
In any case, if you get an error message, always state what that message is.
Hi Guillaume, how can I restrict the number of digits(numbers) to maximum of 4 numbers between each two zeros and the same if the four numbers at the start and end of each row. Because the current code sometimes shows more than four numbers between zeros or at start/end of rows, which is not allowed in my case. Thank you.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!