MATLAB Answers

How do I record the location of a specific value in a set of data?

1 view (last 30 days)
Hello,
I am very new to matlab, and would appreciate advice!
I understand my question is not entirely clear. So I am trying to go through data that looks like:
[1] 0 0 0 0 1 0 1 0 0
And want the code to index until it encounters the first 1 (ignoring the rest of the 1s repeated in the row) then state the distance from the start of the row to the first 1 [so here it would be the distance from column 5 to column 1]
Then ideally it would repeat the same thing for a second row. My 'for' loop is not working, and ideally this code would work for dozens of rows of data. Thank you :)

  0 Comments

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 17 Jun 2020
First_1 = find(x,1) % where x is your row in the loop
Distance = diff(find(x,2))

  3 Comments

Madison Castellanos
Madison Castellanos on 18 Jun 2020
So your answer really worked well for one row, and returns the answer as "5" which is correct, but how do I get it to iterate through several rows?
x2=0 0 0 1 0 0 0
0 1 0 0 0 0 0
0 0 0 0 0 1 0
But if I type
Last=find(exp,3) %so find the non zero values for all three rows, then it returns
Last=
5
10
18
Which is challenging, as I was hoping to get the positions of the 1's in their columns
so for x2 how would i create a loop to return instead?
  • first non zero value is in row 1, col 4
  • second non zero value is in row 2, col 2
  • third non zero value is in row 3, col 6
madhan ravi
madhan ravi on 18 Jun 2020
That is why I specifically commented saying “row” which is “singular”. Loop through through the rows. Preallocate distance as a cell.
Madison Castellanos
Madison Castellanos on 18 Jun 2020
here is my attempt
x=1; %represents number of rows
Distance=cell(3,1); %preallocating distance as an empty cell
for x=1:3 %since only 3 rows in 'exp'
First_1 = find(exp,x); % where x is your row in the loop
if First_1 < 7 %(for 7 columns, but I know this isn't right)
x=x+1
Distance = diff(find(exp,2))
end
end
So I know this code is not correct, but I am still encountering the same error as earlier. Any insight would be appreciated

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!