Randomly changing a value of a matrix

3 views (last 30 days)
I've made a 5x5 matrix of zeros,
I want to randomly change one of the elements to a 1
How would i go about this?
Many thanks

Accepted Answer

the cyclist
the cyclist on 21 Nov 2019
Edited: the cyclist on 21 Nov 2019
M = zeros(5,5);
M(randi(25)) = 1;
This algorithm takes advantage of the power of linear indexing.

More Answers (0)


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!

Translated by