0

how to do this?

i want to place a specific number, like number 2 randomly into a 3x3 of zeros array, it did came out, but the coding still not right and somehow number 1 also appear.

rows = 3;
cols = 3;

M = zeros(rows,cols);

p = randi(2);

rV = randperm(rows);
cV = randperm(cols);


M(rV(2),cV(2))=p

where did i do wrong? any suggestion

2
  • M(randi(numel(M)))=2 ? Commented Apr 13, 2016 at 4:40
  • thanx! that works too.. Commented Apr 13, 2016 at 4:54

2 Answers 2

1

You could also use randi together with linear indexing

m = zeros(3);
m(randi(numel(m))) = 2;
Sign up to request clarification or add additional context in comments.

Comments

0

No need - I've already solved it!

a=[2];
m=zeros(3);
m(randperm(numel(m),numel(a)))=a

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.