Why does this loop return the same value for the variable each time?
Show older comments
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 Comments
Arif Hoq
on 18 Mar 2022
its for the value of z. i guess, all the value of z are same
Nicholas Kavouris
on 18 Mar 2022
Arif Hoq
on 18 Mar 2022
please attach your data
Nicholas Kavouris
on 18 Mar 2022
Edited: Nicholas Kavouris
on 18 Mar 2022
Arif Hoq
on 18 Mar 2022
that's a figure, not the data. attach your variable Temp_F
Nicholas Kavouris
on 18 Mar 2022
@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
on 18 Mar 2022
@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)
Accepted Answer
More Answers (2)
Simon Chan
on 18 Mar 2022
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;
1 Comment
Image Analyst
on 18 Mar 2022
Very nice! 😊
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)]
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!