MATLAB: Creating a Matrix of random numbers

matrixrandom number generator

I'm trying to create a 20×20 matrix of values either -1 or 1, but randomly assigned. How can i do this? I've tried using the randi function but it returns the numbers as a range from -1 1 and so includes 0. any help would be appreciated

Best Answer

possibleValues = [-1, 1];
desiredSize = [5 6];
A = possibleValues(randi(numel(possibleValues), desiredSize))
A = 5×6
-1 1 1 1 1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 1 -1 -1 1 1 -1 1 1 -1 -1 1 -1 1 1 -1
This assumes you want -1 and 1 to be equally likely. If you need an exact number of each possible value:
elements = [repmat(-1, 1, 5), repmat(1, 1, 25)];
order = randperm(numel(elements));
shuffled = reshape(elements(order), desiredSize)
shuffled = 5×6
1 -1 1 1 1 1 1 1 1 1 -1 1 1 1 -1 1 1 1 -1 1 1 1 1 1 -1 1 1 1 1 1
If you need the two numbers not to be equally likely (say 1 three times as likely as -1) there are ways to do this as well.