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

조회 수: 3(최근 30일)
Lily A. Campbell
Lily A. Campbell 2020년 6월 18일
답변: Rajani Mishra 2020년 8월 26일
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
KSSV
KSSV 2020년 6월 18일
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.

댓글을 달려면 로그인하십시오.

답변(1개)

Rajani Mishra
Rajani Mishra 2020년 8월 26일
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!

Translated by