if loop to find values in a variable
10 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
Matt J
2023 年 6 月 8 日
編集済み: Matt J
2023 年 6 月 8 日
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 件のコメント
Matt J
2023 年 6 月 8 日
編集済み: Matt J
2023 年 6 月 8 日
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
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!