matlabconqueso
matlabconqueso

Reputation: 45

How to replace multiple values in a matrix in matlab

I'm trying to turn N number of zeros into a "1". My code works to change only one zero at a time. What is the best way to simultaneously change the zeros into a "1" N number of times?

N=4;
board=zeros(N);
board(randi(numel(board)))=1

Thank you

Edit:

N=4;
board=zeros(N);
x=1;
while (x<=N)
    board(randi(numel(board)))=1;
    x=x+1;
end

Would it be possible to get this to work? It's not giving me an error, but it's not giving me an output either...

Upvotes: 1

Views: 712

Answers (3)

atru
atru

Reputation: 4744

This is one way to do it while avoiding an explicit for loop

N=4;
board=zeros(N);

ind_1s = randperm(N*N);
board(ind_1s(1:N)) = 1; 

This generates random permutations of all matrix indices and then it fills first N with 1s.

Your solution will work too but it needs a condition for cases when the newly chosen index already has a 1 in there

N=4;
board=zeros(N);
x=1;
while (x<=N)
    ind_1s = randi(numel(board));
    if board(ind_1s)==0
        board(ind_1s)=1;
        x=x+1;
    end
end

For large matrices the first one may be better performance wise, but that would need to be check with matlab profiler or simple timing.

Upvotes: 0

Vahe Tshitoyan
Vahe Tshitoyan

Reputation: 1439

You can generate an NxN matrix of 0s with M randomly placed 1s in a single line

myMatrix = reshape(randperm(N^2)<=M, N, N);

Just replace M with N in your specific case.

Upvotes: 0

ammportal
ammportal

Reputation: 991

I am suggesting a small improvement over atru's answer. All you need to do is this:

N=4;
board=zeros(N);
board(randperm(numel(board), N)) = 1;

Here randperm will basically generate N random numbers from the set 1:(N*N) to fill your matrix

Upvotes: 1

Related Questions