Finding the first time a number appears in a matrix

3 visualizzazioni (ultimi 30 giorni)
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.

Risposte (1)

Star Strider
Star Strider il 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
val = 1.1102e-16
idx = 94
[crr,ccc] = ind2sub(size(c),idx) % Convert To Subscripts
crr = 44
ccc = 2
Check = c(crr,ccc) % Check Result (Delete Later)
Check = 0.7000
.
  2 Commenti
Sam Robinson
Sam Robinson il 26 Apr 2021
This doesn't work fully because I just tried it and had a value of 0.7 in my first row but it had my crr as 12, do you know why this is?
Appreciate your help though
Star Strider
Star Strider il 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
c = 7×7
0.6982 0.2813 0.7838 0.1135 0.2605 0.6285 0.4805 0.6335 0.1326 0.5351 0.9037 0.7807 0.5998 0.2855 0.8854 0.6318 0.6203 0.1800 0.7000 0.8871 0.0876 0.9228 0.0353 0.6748 0.8209 0.0847 0.5314 0.4022 0.7950 0.0737 0.1782 0.3322 0.5021 0.1417 0.1283 0.4916 0.2146 0.7357 0.0710 0.6016 0.2754 0.6260 0.9563 0.9825 0.0833 0.0659 0.8694 0.6343 0.6513
ct = c.'; % Transpose
[val,idx] = min(abs(ct(:)-0.7)) % Return Linear Index
val = 0
idx = 19
[ccc,crr] = ind2sub(size(c),idx)
ccc = 5
crr = 3
Check = c(crr,ccc)
Check = 0.7000
.

Accedi per commentare.

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by