Produce 6 different number by only use "randi" and some loops - matlab

I want to only use "randi" this function to produce the 6 different number randomly in matlab ,and the range of these 6 number is 1 ~ 12.
number=randi([1,12],1,6)
c=0;
for n=1:6%when "n" is 1 to 6
while c <= 6 %while c is less equal than 6,do the program below
c = c + 1; %c=c+1
if number(n) == number(c) %when the nth element is equal to cth element
number(n) = randi(12); %produce a random integer in the nth element
c = 0; %the reason why i set c=0 again is because i want to check again whether the new random integer is the same as cth element or not
end
end
end
final_number=number
but the result still show me like
1 "2" 6 11 "2" 3
5 "8" "8" 12 3 1
How do i improve my code to produce 6 different numbers.i don't want to always rely on the convenient matlab instruction too much,so my tags will also write c.hoping someone can help me to improve this

If you're trying to reproduce randsample (or randperm), why not just reproduce the algorithm MATLAB uses? (As far as we can tell...)
This is the Fisher-Yates shuffle. If you have a vector v, each iteration selects a random, previously unused element and puts it at the end of the unselected elements. If you do k iterations, the last k elements of the list are your random sample. If k equals the number of elements in v, you've shuffled the entire array.
function sample = fisher_yates_sample(v, k)
% Select k random elements without replacement from vector v
% if k == numel(v), this is simply a fisher-yates shuffle
for n = 0:k-1
randnum = randi(numel(v)-n); % choose from unused values
% swap elements v(end-n) and v(randnum)
v([end-n, randnum]) = v([randnum, end-n]);
end
sample = v(end-k+1:end);
end
Unlike MATLAB's version, mine requires a vector as input, so to get 6 random values in the range 1:12 you'd call the function like this:
>> fisher_yates_sample(1:12,6)
ans =
5 11 6 10 8 4

Since you're re-selecting single random numbers, when there is one occuring multiple times, why not just re-selecting all numbers at once?
% Initial selecting of random numbers.
number = randi([1, 12], 1, 6)
% While the amount of unique elements in numbers is less than 6:
while (numel(unique(number)) < 6)
% Re-select random numbers.
number = randi([1, 12], 1, 6)
end
And since you wrote, you specifically want to use the randi method, I guess there is a reason, you don't want to use randperm(12, 6)!?

What you are looking for is randperm. It produces a random permutation of a range of integers, so that if you select the first k numbers, you are sure that you get k unique integers in the range [1;n].
In your case, simply call:
randperm(12,6)

Related

I wrote the following code in matlab to randomize and after that round numbers 3 to 8 in 3x4 matrix but i want to not be repeated numbers in rows

i wrote this code for randomize and round numbers
x=3+5*rand(3,4);
for n=1:3
for m=1:4
y(n,m)=round(x(n,m));
end
end
y
Using the randperm() function may be an option. The first argument of randperm() sets the range. In this case randperm(6,4) will generate 4 numbers that are within the range 1 to 6 (a random permuatation of integers in this case permutations of 6). If we add 2 to this result we can generate an array of length 4 that will have values ranging from 3 to 8. Here we can use one for-loop and generate the rows upon each iteration.
Array = zeros(3,4);
for Row = 1: 3
Array(Row,:) = randperm(6,4) + 2;
end
Array
First of all the rand() function returns numbers between 0 and 1, so it probably doesn't make sense to use this function and then round the numbers off. If you're looking for random integers use randi() instead.
With this in mind, the following code produces a 3 by 4 matrix filled with random integers and no repeats:
maxInteger = 12; %change to any number greater than 3x4 = 12
y = randi(maxInteger, 3, 4);
used = [];
for i = 1:numel(y)
while sum(find(used == y(i)))>0
y(i) = randi(maxInteger);
end
used = [used, y(i)];
end
If the while loop takes too long (as might happen with large matrices) consider filling a matrix by pulling and removing elements from a predecided list of integers.

How to check my matrix if its divisible by 12

im new to matlab and i've run into a slight problem. I want to check my matrix that generated random number if they are divisible by 12. Then i want to list number of digit divisible by 12 and the total sum of those.
clc
clear
format compact
a=4
b=0
N=50+a
R=randi([100+a,159+b], 1, N) % generate random no. from 100+a to 159 on a matrix 1xN
s1=0
N1=0
for i = 1
for j= 1:N
if rem(R,12)==0
N1=N1+1;
s1=s1+R(i,j);
else
N1=N1+0;
s1=s1+0;
end
end
end
numberof1=N1
sum1=s1
Your code isn't working because your are calling rem(R, 12) (remainder of all elements) as opposed to the remainder of the specific element (rem(R(i,j), 12)).
The better approach though would be to remove the for loop and generate a logical matrix the size of R that is true when that number is divisible by 12 and false otherwise by passing the entire matrix to rem.
is_divisible_by_12 = rem(R, 12) == 0;
Then we can use this to compute the sum of these by using this logical array as an index into R
subset = R(is_divisible_by_12);
number = numel(subset);
s1 = sum(subset);

Logical statement where all matrix elements must be greater than those in another matrix

I'm looking for a way to test if all elements of a matrix are greater than or equal to their corresponding indexes values in another matrix, and if not to stop evaluating. This is part of an elseif statement for setting a lower bound for values, thus as simplified example:
Lower Bound matrix: A = [4 5 6 7]
New values matrix: B = [7 8 9 10]
Is B>=A then yes, accept and proceed
whereas
Lower Bound matrix: A = [4 5 6 7]
New values matrix: C = [5 3 5 8]
Is C>=A? then no, all elements of C are not greater than A, reject and stop
My solution so far is a bit hackneyed:
Is sum(C>=A) < length(C)? no, then reject and stop
This gives the sum of the true/false values in the comparison C>=A, which if all values of C were greater would equal the length of C, else the sum would be less than the length of C. I keep thinking there's a simple and more elegant solution to this that I'm overlooking and would be grateful for any thoughts. Thanks!
MATLAB has a built-in function for performing this action called all. You can use this on a logical matrix to determine if all values are true. In your case you would pass the logical matrix: B >= A.
A = [4,5,6,7];
B = [7,8,9,10];
all(B(:) >= A(:))
1
Notice that I have used (:) above which ensures that both A and B are column vectors prior to performing the comparison. This way, they can be of any arbitrary dimension and the result of all will always be a scalar.
While you're at it, you may also look into any.
You must indeed rely on logical indexing. To check whether a given matrix B has elements greater than or equal to their corresponding indexes values in another given matrix A you can do something like:
if (sum(sum(B>=A))==numel(A))
%enter if body here
end
The statement B>=A will return a logical matrix with 1 in position (i,j) if B(i,j)>=A(i,j). You then sum all the 1s inside such matrix and then check if such sum is equal to the number of elements (numel()) in A (or B).
In your example. Given
A=[4 5 6 7];
B=[7 8 9 10];
the statement B>=A will return
ans =
1 1 1 1
because all elements in B are greater then elements in A. Sum this vector, you'll get 4. Is the sum (4) equal to the number of elements (4)? Yes. Then all elements in B are greater than or equal to the elements in A.
Note: the double sum() makes your code more robust. It will indeed work also with matrices and not just with vectors. That is because if you do sum() on a matrix, Matlab by default does not return the sum of all its elements, but the sum along the first dimension whose size is different from 1. So if our matrix is:
C =
8 1 6
3 5 7
4 9 2
sum(C) will return
ans =
15 15 15
(Matlab took the sum of every column).
By taking also the sum of such vector we'll get the sum of all the elements.
This ends the quick explanation regarding the nested sum().
I assume by an elegant solution you mean a solution which is more efficient.
Lets create test data:
A = zeros(100000,100000); B = zeros(100000,100000);
Linear Loop
for i = 1:numel(A)
if A(i) < B(i)
display('different')
break
end
end
Logical indexing
if (sum(sum(B>=A))~=numel(A))
display('different')
end
The loop is better when its comes to the best case (first element is smaller):
Elapsed time is 0.000236 seconds. Elapsed time is 0.131802 seconds.
and when its the average case:
Elapsed time is 0.001993 seconds. Elapsed time is 0.196228 seconds.
But we only care about the worst case:
B(end) = 1;
Elapsed time is 8.181473 seconds. Elapsed time is 0.108002 seconds.

Matlab: Array of random integers with no direct repetition

For my experiment I have 20 categories which contain 9 pictures each. I want to show these pictures in a pseudo-random sequence where the only constraint to randomness is that one image may not be followed directly by one of the same category.
So I need something similar to
r = randi([1 20],1,180);
just with an added constraint of two numbers not directly following each other. E.g.
14 8 15 15 7 16 6 4 1 8 is not legitimate, whereas
14 8 15 7 15 16 6 4 1 8 would be.
An alternative way I was thinking of was naming the categories A,B,C,...T, have them repeat 9 times and then shuffle the bunch. But there you run into the same problem I think?
I am an absolute Matlab beginner, so any guidance will be welcome.
The following uses modulo operations to make sure each value is different from the previous one:
m = 20; %// number of categories
n = 180; %// desired number of samples
x = [randi(m)-1 randi(m-1, [1 n-1])];
x = mod(cumsum(x), m) + 1;
How the code works
In the third line, the first entry of x is a random value between 0 and m-1. Each subsequent entry represents the change that, modulo m, will give the next value (this is done in the fourth line).
The key is to choose that change between 1 and m-1 (not between 0 and m-1), to assure consecutive values will be different. In other words, given a value, there are m-1 (not m) choices for the next value.
After the modulo operation, 1 is added to to transform the range of resulting values from 0,...,m-1 to 1,...,m.
Test
Take all (n-1) pairs of consecutive entries in the generated x vector and count occurrences of all (m^2) possible combinations of values:
count = accumarray([x(1:end-1); x(2:end)].', 1, [m m]);
imagesc(count)
axis square
colorbar
The following image has been obtained for m=20; n=1e6;. It is seen that all combinations are (more or less) equally likely, except for pairs with repeated values, which never occur.
You could look for the repetitions in an iterative manner and put new set of integers from the same group [1 20] only into those places where repetitions have occurred. We continue to do so until there are no repetitions left -
interval = [1 20]; %// interval from where the random integers are to be chosen
r = randi(interval,1,180); %// create the first batch of numbers
idx = diff(r)==0; %// logical array, where 1s denote repetitions for first batch
while nnz(idx)~=0
idx = diff(r)==0; %// logical array, where 1s denote repetitions for
%// subsequent batches
rN = randi(interval,1,nnz(idx)); %// new set of random integers to be placed
%// at the positions where repetitions have occured
r(find(idx)+1) = rN; %// place ramdom integers at their respective positions
end

MatLab assigning only the first two variables in

I am trying to write a MatLab function to compute Fibonacci numbers. below is what I have but it comes up with an error about F(0).
??? Attempted to access F(0); index must be a positive integer or logical.
Error in ==> fibonacci at 11
F(0) = 0;
How do I tell matlab that the first two values in the array are 0 and 1??
function F = fibonacci( n )
%A fibonacci sequence is where the next term in the series is given by the
%sum of the pervious two terms
%Only valid if n is greater than or equal to 2
if n >= 2 ;
%Make an array with n terms
F = zeros (1,n);
%run a for loop from 2 to n
for i = 2:n;
F(0) = 0;
F(1) = 1;
F(i) = F(i-1) + F(i-2)
end
end
end
Your formatting is a bit off, but it seems like you are assigning a value to the zero-index of an array. As far as I know MatLab uses 1 as the index of the first item in an array.
If you change your if n>=2 to if >=3 and set the 1 and 2 index items instead of the 0 and 1 items you should be well on your way.
See also Is zero based indexing available in MATLAB
MATLAB uses 1-based indexing, which means you should rewrite indices to reflect this shift, by replacing your n variables with n+1. This starts the fibonacci at 0, but indexed to 1, 1 at 2, 1 at 3, 2 at 4, 3 at 5, and so on to your "n"th term, now be indexed at n+1.