How to find first instance of a value in array?
614 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Tawsif Mostafiz
le 4 Juil 2021
Commenté : Tawsif Mostafiz
le 5 Juil 2021
Hi, I am writing a code that as follows:
arr(p)=abs(c); %absolute value of c
if(arr(p)<1)
if(arr(p)>0.9)
array(t)=white1;
cor(t)=arr(p); %correlation for c>.95 && c<1
t=t+1;
end
end
maximum=max(cor); %maximum value of cor(t)
Now, I am trying to find the first instance the value of maximum comes in the "arr" Array.
I have tried the following:
1.
for v=1:x
if(maximum==arr(v))
% x=find(arr==maximum);
u=u+1;
if(u==1) %making sure only the first max value is taken
q=value(v); %q is becoming always 0.5,have to fix it
end
end
end
and,
2.
x=find(arr==maximum);
and,
3.
x = find(maximum == arr,'first') ;
In the 1st and 2nd try, when I use fprintf to detect the x, it prints blank, such as,
"x is "
In the 3rd try the following error occurs,
Second argument must be a positive scalar integer.
How can I fix it?
0 commentaires
Réponse acceptée
Steven Lord
le 4 Juil 2021
You could use logical indexing.
rng('default')
c = randn(1, 10)
arr = abs(c)
% Overwrite those values in arr that are out of bounds with NaN. I'm using
% wider bounds to show the technique with a small data set.
arr(arr > 1.5) = NaN
arr(arr < 0.5) = NaN
[value, location] = max(arr, [], 'omitnan')
If all you're interested in is the value and not its location in c you could delete the elements of arr that fall out of bounds.
arr2 = abs(c);
arr2(arr2 > 1.5) = [];
arr2(arr2 < 0.5) = []
[value2, location2] = max(arr2)
location2 is not the same as location because arr2 does not have the same number of elements as either arr or c.
Plus de réponses (2)
Jiro Doke
le 4 Juil 2021
Is this what you're looking for?
maximum = 5;
arr = [2 4 3 5 7 3 4];
find(arr == maximum, 1)
1 commentaire
Tawsif Mostafiz
le 4 Juil 2021
Modifié(e) : Tawsif Mostafiz
le 4 Juil 2021
Voir également
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!