How can I track the random numbers generated by rand(2,2)?

2 views (last 30 days)
I need to find the random sequance that minimizes an objective function when the program is run multiple times. I looked into "seeding" and could not get it to work for producing a random 2x2 matrix. I am minimizing distance between points in a matrix to random vectors in a matrix, while producing a K-means algorithm. My code is as follows:
X = rand(5, 2);
Y = randn(2,2);
i=1;
while i<10
a = sum((X-Y(1,:)).*(X-Y(1,:)),2);
%disp(a);
b = sum((X-Y(2,:)).*(X-Y(2,:)),2);
%disp(b);
[val,assign] = min([a b],[],2);
cluster1idx = find(assign ==1);
Y(1,:)= mean(X(cluster1idx,:));
cluster2idx = find(assign ==2);
Y(2,:)= mean(X(cluster2idx,:));
a = sum((X(cluster1idx,:)-Y(1,:)).*(X(cluster1idx,:)-Y(1,:)),2); %cluster 1 indx
b = sum((X(cluster2idx,:)-Y(2,:)).*(X(cluster2idx, :)-Y(2,:)),2);%cluster 2 idx
i=i+1;
end
where I want to be able to track the values generated by rand(5,2) and rand(2,2) when this is iterated many times.
  1 Comment
KSSV
KSSV on 18 Jun 2020
find(assign==1)
The above will give you empty matrix...so you cannot save it in Y (you are overwrititng it). What exactly you want? Code is messy.

Sign in to comment.

Answers (1)

Rajani Mishra
Rajani Mishra on 26 Aug 2020
I assume you want to know how to solve the issue of vector b and cluster2idx being empty, as the question is not completely clear. I ran your code multiple times, majority times vector b and cluster2idx was empty or had values of the order 10-4. In one of the iterations b has NaN values that may be causing this issue.
I tried random number generator with seed (refer to below code)
rng(100,'philox')
s = rng;
X = rand(5, 2);
Y = randn(2,2);
i=1;
while i<10
a = sum((X-Y(1,:)).*(X-Y(1,:)),2);
%disp(a);
b = sum((X-Y(2,:)).*(X-Y(2,:)),2);
%disp(b);
[val,assign] = min([a b],[],2);
cluster1idx = find(assign ==1);
Y(1,:)= mean(X(cluster1idx,:));
cluster2idx = find(assign ==2);
Y(2,:)= mean(X(cluster2idx,:));
a = sum((X(cluster1idx,:)-Y(1,:)).*(X(cluster1idx,:)-Y(1,:)),2); %cluster 1 indx
b = sum((X(cluster2idx,:)-Y(2,:)).*(X(cluster2idx, :)-Y(2,:)),2);%cluster 2 idx
i=i+1;
end
To learn more about rng function refer: https://www.mathworks.com/help/matlab/ref/rng.html

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!