Hello a question please.
I have matrix P with size (452*500). I want to select random selection with roulette wheel selection. I write something:
r=rand;
c=reshape(p,1,[]);
c1=cumsum(c);
j=find(r<=c1,1,'first');
[j1 j2]=ind2sub(size(p),j);
end
but I want to remove part " c=reshape(p,1,[]);" and create cumulative matrix of p directly without reshaping it to matrix c. How can I do it?
Thank you.

 채택된 답변

Stephen23
Stephen23 2015년 2월 3일
편집: Stephen23 2015년 2월 3일

0 개 추천

Something like this? :
r = rand;
jj = find(r<=cumsum(p(:)),1,'first');
[j1,j2] = ind2sub(size(p),jj);
Note I also renamed your variable j, which is also one of names of the inbuilt imaginary unit .

댓글 수: 3

fatema saba
fatema saba 2015년 2월 3일
Thank you,but is there any way to create cumulative matrix of p directly. I mean, for example p is matrix "(500,500). I want to create cumulative mtrix of p for example named pcum that it's size is "(500,500)".
Stephen23
Stephen23 2015년 2월 3일
편집: Stephen23 2015년 2월 3일
This depend on you and what you want your code to do. Read the documentation for cumsum, you will see that it always calculates the sum along one dimension (row, column, etc). Lets have a look at what the documentation says:
  • If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements of A.
  • If A is a matrix, then cumsum(A) returns a matrix containing the cumulative sums for each column of A.
...
  • B = cumsum(A,dim) returns the cumulative sum of the elements along dimension dim. For example, if A is a matrix, then cumsum(A,2) returns the cumulative sum of each row.
So the documentation tells us that if you want a column vector of cumulative sums of each row (or a row of the columns, etc), then the answer to your question is yes, you can do it without reshaping the matrix p first. In every case it is summing only along one dimension, so if you want the cumulative sum over all elements of a matrix, you will have to convert it first to a vector, and probably the neatest way of doing this is using p(:).
fatema saba
fatema saba 2015년 2월 3일
Thank you for your kindness and clear explanation.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2015년 2월 3일

댓글:

2015년 2월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by