Finding the first time a number appears in a matrix
4 views (last 30 days)
Show older comments
I have matrix c and I am looking to find the first time the number 0.7 appears in the matrix searching row by row.
I have this code to search for it in the first row "columnindex=find(c(1,:)>=0.7,1,'first');" but if it does not appear in the first row how do I search the row below and so on?
Thank you.
0 Comments
Answers (1)
Star Strider
on 26 Apr 2021
Try this —
c = randi([650 750], 50)*1E-3; % Create Matrix
[val,idx] = min(abs(c(:)-0.7)) % Minimum Of Absolute Difference (Linear Index
[crr,ccc] = ind2sub(size(c),idx) % Convert To Subscripts
Check = c(crr,ccc) % Check Result (Delete Later)
.
2 Comments
Star Strider
on 26 Apr 2021
My pleasure!
The way llinear indexing works, it should scan the first column, then the second column, and so forth.
Transposing ‘c’ first will likely create the linear index appropriately with respect to the ‘ct(:)’ vector to give the result you want, then reversing ‘crr’ and ‘ccc’ in the ind2sub output —
c = rand(7); % Create Matrix
c(3,5) = 0.7 % Specific Element Substitution
ct = c.'; % Transpose
[val,idx] = min(abs(ct(:)-0.7)) % Return Linear Index
[ccc,crr] = ind2sub(size(c),idx)
Check = c(crr,ccc)
.
See Also
Categories
Find more on Matrices and Arrays 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!