if loop to find values in a variable
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have 2 arrays of numbers, t and Q. I want to use an if loop to do the following:
- find if tfind is present in the variable t.
- if this number is present, find the index of the number within this array.
- find the number in the variable Q which corresponds to this index
my code runs, but the variable c is empty. Can anybody help?
t = [4 5 7 8 10 11 12 15 17 20 22 24 26 27 28];
Q = [1 3 4 1 5 8 4 2 6 1 4 2 8 3 5];
p = 10;
np = 3;
for i = 1:p
c = [];
for j = 1:np
tfind = (j-1)*p+i
if ismember(t, tfind) %find if tfind is in t
loc = find(t=tfind) % find the index of tfind within t
q = Q(loc) %find the number in Q which corresponds to this index
end
c = [c;q] %assign the values of q to new variable
end
end
0 commentaires
Réponses (1)
Matt J
le 8 Juin 2023
Modifié(e) : Matt J
le 8 Juin 2023
One possibility
t = [4 5 7 8 10 11 12 15 17 20 22 24 26 27 28];
Q = [1 3 4 1 5 8 4 2 6 1 4 2 8 3 5];
p = 10;
np = 3;
c = cell(1,p*np); k=0;
for i = 1:p
for j = 1:np
tfind = (j-1)*p+i;
k=k+1;
c{k}=Q(t==tfind);
end
end
c=cell2mat(c)
2 commentaires
Matt J
le 8 Juin 2023
Modifié(e) : Matt J
le 8 Juin 2023
I want to end up with 3 rows of data that I can take a mean from.
So, c is meant to have np=3 rows? How many columns?
Maybe this is what you mean:
t = [4 5 7 8 10 11 12 15 17 20 22 24 26 27 28];
Q = [1 3 4 1 5 8 4 2 6 1 4 2 8 3 5];
p = 10;
Lti = 30;
np = Lti/p;
c = nan(np,1); %ensemble average signal
for j = 1:np
for i = 1:p
tfind = (j-1)*p+i;
c(j) = mean( Q(t==tfind) );
end
end
c %three rows
Voir également
Catégories
En savoir plus sur Data Type Conversion 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!