if loop to find values in a variable

5 次查看(过去 30 天)
C.G.
C.G. 2023-6-8
编辑: Matt J 2023-6-8
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

回答(1 个)

Matt J
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)
c = 1×15
8 4 4 1 2 3 2 8 4 6 3 1 5 5 1
  2 个评论
C.G.
C.G. 2023-6-8
编辑:Matt J 2023-6-8
Thank you for your response.
Your answer didnt quite answer my question but got me closer to it.
What I want it to do, is to loop through and save each iteration of c_s rather than just the last one. I want to end up with 3 rows of data that I can take a mean from. Do you know how I can do this?
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 = []; %ensemble average signal
for i = 1:p
c_s = []; %sediment flux values equal to each second of the period
for j = 1:np
tfind = (j-1)*p+i;
c_s = Q(t==tfind);
end
c = [c;mean(c_s)];
end
c
c = 10×1
NaN 4 NaN 2 NaN 8 3 5 NaN NaN
Matt J
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
c = 3×1
5 1 NaN

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by