Changing array size while using Find Function

2 views (last 30 days)
Amit
Amit on 19 Dec 2013
Commented: Amit on 19 Dec 2013
The matlab answers have been very helpful to me and I am grateful to all you guys. This is my first question and I hope you can help me. I have a big matrix (lets say Rs (50000 x 7), this is done as memory pre-allocation). The columns 3,4,6 are more often than not 0. What I need to do in the matrix is in every loop pick a column and utilize one of the non-zero elements.
toPick = find(Rs(1:flag_Rs,3));
rand_pick = toPick(randperm(numel(toPick),1));
toPick finds the indices in that column which are available and picks a random index (rand_pick) to do the operation. flag_Rs is a flag which has the index of the last row in Rs matrix, that has been utilized. I have used flag_Rs to speed up the code.
The issue is that i have been reusing the toPick variable and in every loop (the code loops for many time, Monte carlo type simulation) the size of toPick varies. Both of these steps are the most time consuming in my code and I am hoping to reduce this time, using your suggestions!

Answers (1)

Walter Roberson
Walter Roberson on 19 Dec 2013
toPick = find(Rs(1:flag_Rs,3));
rand_pick = toPick(randi(numel(ToPick)));
Notice this will give you a row number, not the value directly.
t = Rs(1:flag_Rs,3);
t2 = t(t~=0);
rand_pick = t2(randi(length(t2)));
This form would return the value itself; it has also been reformulated to not use find()
  1 Comment
Amit
Amit on 19 Dec 2013
I need the index as well. That's why I was limited to find function (unless there is some other function). Moreover, on testing this method, this appears to be slower than the find method in the question.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!