Why does this loop return the same value for the variable each time?
이전 댓글 표시
Why does this loop return '4' every iteration for temp status? attached is a plot of Z, which should not return temp_status(i) as 4 each iteration as many values in z are above 15 and others below-15?
temp_status=[];
x=diff(Temp_F);
z=conv(x,ones(300,1),"same");
figure()
y=plot(z)
for i=1:length(z)
if z>=15
temp_status(i)=1;
elseif z>=-15 & z<15
temp_status(i)=2;
elseif z<-15
temp_status(i)=3;
else
temp_status(i)=4;
end
end
댓글 수: 9
Arif Hoq
2022년 3월 18일
its for the value of z. i guess, all the value of z are same
Nicholas Kavouris
2022년 3월 18일
Arif Hoq
2022년 3월 18일
please attach your data
Nicholas Kavouris
2022년 3월 18일
편집: Nicholas Kavouris
2022년 3월 18일
Arif Hoq
2022년 3월 18일
that's a figure, not the data. attach your variable Temp_F
Nicholas Kavouris
2022년 3월 18일
@Nicholas Kavouris you should use z(i)
edit: or don't use a loop
temp_status=4*ones(size(z));
temp_status(z>=15) = 1;
temp_status(z>=-15 & z<15) = 2;
temp_status(z<-15) = 3;
Nicholas Kavouris
2022년 3월 18일
@Nicholas Kavouris it seems weird at first but it's a really cool feature in matlab. Once you use it a lot you will hate other languages that don't have this feature.
Here is a toy example,
temp_status = [4 4 4 4]; % for example all start as 4
z=[10 12 15 16]; % the comparable
idxs = z>=15 % the conditional indexes
temp_status(idxs) = 1 % matlab recognizes logical indexing and only applies the assignment to the true "1" indices.
Only the 3rd and 4th values were changed from 4 to 1 because only indeces 3 and 4 were true (1)
채택된 답변
추가 답변 (2개)
Simon Chan
2022년 3월 18일
Just an addition:
x=diff(Temp_F);
z=conv(x,ones(300,1),"same");
temp_status = (z>15) + (z>=-15 & z<15)*2 + (z<-15)*3;
try this:
A=load('Temp_F.mat');
temp_status=[];
Temp_F=A.Temp_F;
x=diff(Temp_F);
z=conv(x,ones(300,1));
figure()
y=plot(z);
for i=1:length(z)
if z(i)>=15
temp_status(i)=1;
elseif z(i)<=-15
temp_status(i)=3;
elseif z(i) > -15 & z(i) <15
temp_status(i)=2;
else
temp_status(i)=4
end
end
T=temp_status';
Z=z';
matrix=[Z(1:6) T(1:6)]
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
