필터 지우기
필터 지우기

Retrieving a random element from each row in a matrix

조회 수: 6 (최근 30일)
Lui
Lui 2019년 5월 23일
댓글: Star Strider 2019년 5월 24일
hi everyone
I have a 20 by 10 matrix. I am running the following code to retrieve a random element from each row of the matrix. In this case, I need to create a 20 by 1 matrix at the end. I have written the following code but it does give me a shuffle of the first column alone.
sz=size(R,1);
B=zeros(sz,1);
i=1:20
% for n=1:100
for j=1
for i=1:20
for row=1:20
M(i,j)=randi(length(R),20,1);
B(i,j)=R(M(i,j));
end
end
end
% end
  댓글 수: 2
Alex Mcaulley
Alex Mcaulley 2019년 5월 23일
What is your question? Do you have any issue?
Lui
Lui 2019년 5월 23일
The code does not yield the desired results and would appreciate if someone helped point out where it is wrong or an alternative methods

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

채택된 답변

Star Strider
Star Strider 2019년 5월 23일
It is likely easier to use the sub2ind funciton to create linear indices into ‘R’ from a defined list of random column subscripts:
R=randi(1000,20,10);
idx = sub2ind(size(R), (1:size(R,1))', randi(size(R,2),size(R,1),1));
B = R(idx)
The second argument defines the row indices and the third defines the random column indices.
See if that does what you want.
  댓글 수: 13
Lui
Lui 2019년 5월 24일
I am grateful.
Just for curiosity sake, if I were to use randi with data which is not normally distributed, the results would be normally distributed. What is the alternative to ensure that the sample data maintains follows its initial distribution?
Star Strider
Star Strider 2019년 5월 24일
As always, my pleasure.
The output of the randi function is uniformly distributed, not normally distributed. If you were to use the normal distribution instead (the randn function being one such), and you did not change the mean and standard deviation to create the ‘R’ matrix, the data would remain normally distributed.
If you do not otherwise change the parameters of the distribution you are using to create the matrix, the matrix should retain the properties of that distribution, regardless of how you sample it.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by