How to put in a condition from if/ifelse statements in a fprintf string.

6 views (last 30 days)
I am trying to include my condition given from an if/ifelse statement inside of a string.
%OUTPUT formatted text showing the temperature, condition of day, and same day(s) temperature.
january21 = [74 60 54 61 54 57 49 41 37 45 45 38 42 58 55 48 55 56 55 55 55 57 60 65 72 71 60 48 56 60 70];
temp = january21(userinput);
if temp < 60
disp 'cold day'
elseif (temp >= 60)||(tempt<= 84)
disp 'pleasant day'
elseif temp >= 85
disp 'hot day'
end
fprintf ('For January %d, it was %0.2f degrees Fahrenheit, a %d \n', userinput, temp, condition);
I want it to be able to utilize the last %d to put whether it is a pleasant, hot, or cold day. I am unsure of how to get it to put the results of the if statements into the string.

Accepted Answer

Jan
Jan on 6 Jul 2021
Edited: Jan on 6 Jul 2021
january21 = [74 60 54 61 54 57 49 41 37 45 45 38 42 58 55 48 55 56 55 ...
55 55 57 60 65 72 71 60 48 56 60 70];
temp = january21(userinput);
if temp < 60
cond = 'cold day'; % [EDITED] Typos fixed: "cond = " inserted.
elseif temp <= 84
cond = 'pleasant day';
else % Not needed anymore: if temp >= 85
cond = 'hot day';
end
fprintf('For January %d, it was %0.2f degrees Fahrenheit, a %s\n', ...
userinput, temp, cond);
Your IF conditions are buggy:
  • (temp >= 60) || (tempt<= 84) is TRUE for all values >= 60. So temp >= 85 cannot be reached ever. Replace || by && to let it work.
  • "tempt" has an additional t.
  • After you have tested for < 60, there is no reason to check for >= 60 in the next branch.

More Answers (0)

Categories

Find more on Characters and Strings 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!