How can I generate a random number in MATLAB between 13 and 20?
If you are looking for Uniformly distributed pseudorandom integers use:
randi([13, 20])
http://www.mathworks.com/help/techdoc/ref/rand.html
n = 13 + (rand(1) * 7);
r = 13 + 7.*rand(100,1);
Where 100,1 is the size of the desidered vector
ocw.mit.edu is a great resource that has helped me a bunch. randi is the best option, but if your into number fun try using the floor function with rand to get what you want.
I drew a number line and came up with
floor(rand*8) + 13
You can also use:
round(mod(rand.*max,max-1))+min
Generate values from the uniform distribution on the
interval [a, b].
r = a + (b-a).*rand(100,1);
Best solution is randint , but this function produce integer numbers.
You can use rand with rounding function
r = round(a + (b-a).*rand(m,n));
This produces Real random number between a and b , size of output matrix is m*n
if you are looking to generate all the number within a specific rang randomly then you can try
r = randi([a b],1,d)
a = start point
b = end point
d = how many number you want to generate but keep in mind that d should be less than or equal to b-a
If you need a floating random number between 13 and 20
(20-13).*rand(1) + 13
If you need an integer random number between 13 and 20
floor((21-13).*rand(1) + 13)
Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21
Related
This question already has answers here:
Generate a random number in a certain range in MATLAB
(9 answers)
Closed 3 years ago.
how can I create a vector with a specific # of values that are drawn from a decided range?
repeats are welcomed as long as they occur randomly.
for example a vector of 5 values all of which are integers between 1 and 80
ps I am working with the 2019 edition of Matlab
You can use rand function; rand gives a random value between 0 and 1, but for a range, you may use the following formula.
lowest_val = -10
range = 20 % [-10, 10]
rand_vec = lowest_val + (range)*rand(10,1) % here the range is [-10, 10]
(20)*rand(10,1) will give a random value between 0 and 20, add -10 to it, the range becomes -10 to 10.
For your case, you may use
lowest_val = 1
range = 79 % [1, 80]
rand_vec = lowest_val + (range)*rand(10,1)
(80)*rand(10,1) will give a random value between 0 and 79, add 1 to it, the range becomes 1 to 80
You may use randperm if you don't want repetitions.
Depends whether they have to be integers or can be 'real' (floating point) numbers. Also, do you want the values 1 and 80 to be included?
In any case, there is this matlab help very useful.
As usually when working with random numbers you need to initialize the random generator.
rng(0,'twister');
This is used for you to be able to reproduce your results, so beware if you always use the same seed (0 in this case) you will always get the same results.
the typical trick to randomize that is to use the current time as seed,
rng(posixtime(datetime('now')),'twister');
Given that you said you wanted an array of 5 numbers,
N = 5;
rand(N,M) returns a matrix of NxM uniformly distributed numbers in the interval (0,1), then you need the following transformation to bring them to your interval (a,b) ((1,80) in your case)
a = 1;
b = 80;
r = (b-a).*rand(N,1) + a;
output:
>> a = 1;
b = 80;
r = (b-a).*rand(N,1) + a
r =
65.5670
69.6269
7.6704
32.5828
21.5298
If you were looking for integers in the interval [1,80] (note that now the interval includes the values 1 and 80), then this would do it,
r = randi(80,N,1);
output:
>> r = randi(80,N,1)
r =
65
35
73
15
22
I have a vector of certain size and I want to reshape it into a square matrix. Here is an example: Let's say the vector is of size 784. Then I would create a matrix of size 28x28. In Matlab I would do it with the following command:
reshape(x,28,28)
Of course it can be possible that it is not possible to have an exact square matrix. In this case the matrix should as squarish as possible.
How can I do this calculation? That means how can I calculate the values a and b in reshape(x,a,b)?
Start with a equal to the square root of numel(x) rounded down. If that number doesn't divide numel(x), subtract 1 and try again. That way you end with a equal to the closest integer to sqrt(x) (from below) that divides numel(x). b would then be numel(x)/a, but you can simply use [] as the third argument to reshape:
a = floor(sqrt(numel(x)));
while mod(x,a)
a = a-1;
end
result = reshape(x,a,[]);
Example:
x = 1:20;
gives
result =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
One possible approach:
x = rand(1, 784);
divisors = find(rem(numel(x), 1:numel(x)) == 0);
[~, idx] = min(abs(divisors - sqrt(numel(x))));
x = reshape(x, divisors(idx), numel(x) / divisors(idx));
Let me explain:
Suppose you have a vector named x:
x = rand(1, 784);
First, you find the divisors of the size of x:
divisors = find(rem(numel(x), 1:numel(x)) == 0);
Then, you proceed to choose the divisor which is closest to the square root of x's size:
[~, idx] = min(abs(divisors - sqrt(numel(x))));
Finally, you reshape x using that divisor (and the corresponding multiple):
x = reshape(x, divisors(idx), numel(x) / divisors(idx));
It is not a simple problem to find closest factors of an integer. You need to use the MATLAB answers to the question Input an integer, find the two closest integers which, when multiplied, equal the input. From that question if you use the answer that provides the function findIntegerFactorsCloseToSquarRoot, you can use the following code to reshape.
[a, b] = findIntegerFactorsCloseToSquarRoot(numel(x));
reshape(x, a, b);
I suggest you to first check whether the number is prime or not by isprime(784).
Then you can use prime_factors = factor(784) to get the integer factorization of the number. (Depending on the MATLAB version you may use ifactor(784))
The rest needs just a little more work on prime_factors.
If I want to generate a random series of fixed point number after decimal and also before decimal
for example
0.112,1.110,1.520,-2.540,-0.001
etc in given range suppose [-4,4].
Is there any command to generate such random number and store in any array?
To Generate values from the uniform distribution on the interval [a, b].
r = a + (b-a).*rand(size,1);
Example :
>> r = -4 + (4-(-4)).*rand(10,1) % 10 random numbers
r =
3.6952
-3.9629
2.1993
2.5384
2.9496
-3.3245
-0.8017
-1.9210
2.4005
-0.5487
I would like to get the error rate of 2 vectors?
like
# incorrect numbers 6
error rate = ______________________ = ____
# total numbers(size) 15
here are 15 numbers, 9 are correct
x is the true answer (the reference), and y is vector with answers
I would like to compare them and get error rate:
x= [1 ,1,1, 1,1, 1,1,1,1,1, 1,-1,-1,-1,-1]
y= [-1,1,1,-1,1,-1,1,1,1,1,-1, 1,-1, 1,-1]
Also is it corret what I am doing?
Ok I was wrong about the formula I updated it.
If you want the error rate, then you want the number of incorrect values divided by the total number of values. You can do this using the relational operator ~= and the function MEAN:
errorRate = mean(x ~= y);
Another version that works:
length(find(x~=y))/length(y)
I have a matrix containing 4320 entries
for example:
P=[ 26 29 31 33 35 26 29 ..........25]
I want to create 180 matrices and every matrix contains 24 entries,i.e
the 1st matrix contains the 1st 24 entries
the 2nd matrix contains the 2nd 24 entries and so on
I know a simple method but it will take a long time which is:
P1=P(1:24);P2=P(25:48),..........P180=P(4297:4320)
and it is dificult since I have huge number of entries for
the original matrix P
thanks
I'm going to go ahead and assume this is MATLAB-related, in which case you'd use the reshape function:
Px = reshape(P, 24, []);
Px will now be a proper matrix, and you can access each of the 180 "matrices" (actually row vectors, you seem to be confusing the two) by simple MATLAB syntax:
P100 = P(:,100);
You can loop through the items in the index, counting up, creating a new matrix every 24 entries. Modular arithmetic might help:
foreach (var currentIndexInLargerMatrix : int = 0 to 4320)
begin
matrixToPutItIn := currentIndexInLargerMatrix div 24;
indexInNewMatrix := currentIndexInLargerMatrix mod 24;
end
in many languages the modulus (remainder) operator is either "mod" or "%".
"div" here denotes integer division. Most languages just use the virgule (slash) "/".
This obviously isn't complete code, but should get you started.
I think You's answer is the best way to approach your problem, where each submatrix is stored as a row or column in a larger matrix and is retrieved by simply indexing into that larger matrix.
However, if you really want/need to create 180 separate variables labeled P1 through P180, the way to do this has been discussed in other questions, like this one. In your case, you could use the function EVAL like so:
for iMatrix = 1:180 %# Loop 180 times
tempP = P((1:24)+24*(iMatrix-1)); %# Get your submatrix
eval(['P' int2str(iMatrix) ' = tempP;']); %# Create a new variable
end