I don't know what is wrong with my code when recreating a table

There's this table I need to create, in which, depending on the time(t), the value of Clo and Met changes. My code is:
t = 0:0.5:24;
for i = 0:0.5:24
if t(i)>=0 && t(i)<8
Clo = 3;
Met = 0.4;
end
if t(i)>=8 && t(i)<12
Clo = 1;
Met = 1;
elseif t(i)>=12 && t(i)<17
Clo = 0.5;
Met = 1.6;
elseif t(i)>=17 && t(i)<22
Clo = 1;
Met = 0.9;
elseif t(i)>=22 && t(i)<24
Clo = 2.5;
Met = 0.4;
else
plot(t,Clo,'g');
xlabel ('Time (hours)');
ylabel ('Clo');
end
end

Answers (1)

loop indices must be positive integers or logical values. In your code, you're trying to use fraction values as index. Also, your plot command is inside an else branch. The below modifications might help.
t = 0:0.5:24;
Clo = zeros(size(t));
Met = zeros(size(t));
for idx = 1:numel(t)
if t(idx)>=0 && t(idx)<8
Clo(idx) = 3;
Met(idx) = 0.4;
elseif t(idx)>=8 && t(idx)<12
Clo(idx) = 1;
Met(idx) = 1;
elseif t(idx)>=12 && t(idx)<17
Clo(idx) = 0.5;
Met(idx) = 1.6;
elseif t(idx)>=17 && t(idx)<22
Clo(idx) = 1;
Met(idx) = 0.9;
elseif t(idx)>=22 && t(idx)<=24
Clo(idx) = 2.5;
Met(idx) = 0.4;
end
end
plot(t, Clo,'g')
xlabel ('Time (hours)')
ylabel ('Clo')
figure
plot(t, Met,'r')
xlabel ('Time (hours)')
ylabel ('Met')

6 Comments

Okay thank you very much. I appreciate it a lot.
I don't know why but the plots are completely empty which I wasn't expecting.
@Sarah Kneer Are you executing the exact script as mentioned in the answer? I'm getting output in my end (refer the attached image) with that script.
Works for me, copied verbatim:
t = 0:0.5:24;
Clo = zeros(size(t));
Met = zeros(size(t));
for idx = 1:numel(t)
if t(idx)>=0 && t(idx)<8
Clo(idx) = 3;
Met(idx) = 0.4;
elseif t(idx)>=8 && t(idx)<12
Clo(idx) = 1;
Met(idx) = 1;
elseif t(idx)>=12 && t(idx)<17
Clo(idx) = 0.5;
Met(idx) = 1.6;
elseif t(idx)>=17 && t(idx)<22
Clo(idx) = 1;
Met(idx) = 0.9;
elseif t(idx)>=22 && t(idx)<=24
Clo(idx) = 2.5;
Met(idx) = 0.4;
end
end
plot(t, Clo,'g')
xlabel ('Time (hours)')
ylabel ('Clo')
figure
plot(t, Met,'r')
xlabel ('Time (hours)')
ylabel ('Met')
I got it know, I missed the (i) after Clo and Met. Thanks.
It's also worth noting that the loop in this code is unnecessary:
t = 0:0.5:24;
Clo = zeros(size(t));
Met = zeros(size(t));
i = t>=0 & t<8
Clo(i) = 3;
Met(i) = 0.4;
i = t>=8 && t<12
Clo(i) = 1;
Met(i) = 1;
i = t>=12 && t<17
Clo(i) = 0.5;
Met(i) = 1.6;
i = t>=17 && t<22
Clo(i) = 1;
Met(i) = 0.9;
i = t>=22 && t<=24
Clo(i) = 2.5;
Met(i) = 0.4;

This question is closed.

Tags

Asked:

on 12 Nov 2020

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!