How can I find the first constant in an array per row that matches a certain absolute value?

I'm trying to find exit times from a simulation. My results are saved in an array/matrix. Each row represents the values of my 1-D random walk. I'm trying to find how long it takes on average to reach some point k.
I first created a smaller array to play with first, and tried using the function
[CODE] [i, j] = find( abs(test_array) == 9); [i, j] [\CODE]
So this gives me a two-column array, with the first column being my row and second column being the position in the row at which abs(9) occurs. But I only want to find the very first occurrence per row. Looking through the documentation I found the 'first' argument, so I tried:
[CODE] [i, j] = find(abs(test_array) == 9, 5, 'first') [\CODE] (for an array with 5 rows. That didn't work though. I also tried transposing it and running the above, but since it goes down each column, it finds multiple points per column rather than just one per column (when transposed) or one per row (as I originally wanted).

 Accepted Answer

This will give you an array with the row number and corresponding first occurrence of the value you want.
If a row does not have the value, it will not have a row in the array I made.
A = [1 2 9; ...
1 9 3; ...
9 4 5; ...
9 9 9; ...
9 9 1; ...
2 9 2];
[i j] = find(A==9);
[first_i,idx] = unique(i,'first')
first_j = j(idx)
[first_i first_j]

More Answers (2)

Instead of
find(abs(test_array) == 9, 5, 'first')
you want
find(abs(test_array) == 9, 1, 'first')
because you want the just 1 instance, not the first 5.
See
doc find
for details.

2 Comments

Ok, I think I need to be more explicit. I want the first instance per row, not just one instance. Using the 1 as second argument, my [i, j] just has two values: one row, and one column.
DO I maybe just need to do that, but loop through the rrows?
My bad. I did not read your question carefully enough. Will mull a bit more.

Sign in to comment.

You can do this with accumarray:
[ii,jj] = find(abs(test_array) == 9);
col = accumarray(ii, jj, [size(x,1) 1], @(x) min(x));
Though it may be more legible to just loop over the rows.

Categories

Community Treasure Hunt

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

Start Hunting!