MATLAB: Generate array of Different random floating numbers in a specific range

floatrandomrange

Dear all, I am going to generate an array of Different random floating numbers in a specific range( such as range of 1, 100) in MATLAB. randperm is creating integer, but I want float numbers , preferable with 1 decimal point. Like 20.1 , 34.2 , 20.2, 27.4 Any help is really appreciated . Thanks

Best Answer

If you want 150 numbers in the range of 1-100, try this (small modification of my prior code):
numberOfElementsNeeded = 150;
while true % Loop until we get the required number of elements.
% Create an array of what should be more than enough numbers with 1 decimal
% place.
% We use more than enough in case there are duplicates that we need to remove.
% It was specified that they all need to be different so there's a
% possibility that some may need to be removed (if there are duplicates).
m = double(int32(rand(3*numberOfElementsNeeded,1) * 1000)) / 10;
% Find out if any happen to be identical.
mUnique = unique(m);
% unique() sorts them. Randomize them to undo the sort
finalArray = m(randperm(length(mUnique)));
% Grab only the number of elements that we need.
numElementsToTake = min([numberOfElementsNeeded length(finalArray)]);
% See if we have enough.
if numElementsToTake == numberOfElementsNeeded
% If we have enough, then break out of the loop.
break;
end
% If we didn't get enough, try again.
end
% Take just numberOfElementsNeeded of them
finalArray = finalArray(1:numberOfElementsNeeded);
% Print out to command window
finalArray
I just changed the line before the for loop to
numberOfElementsNeeded = 150;
and added the line
finalArray = finalArray(1:numberOfElementsNeeded);
after the loop.