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

12 ビュー (過去 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

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by