I am having trouble getting the code to display how many days AND which days of the month things are occurring on (lines 29 and 36 in the script image). See attached images.

3 views (last 30 days)
Issue: The command for line 29 should show "1, 7, 9, 14, 15, 18, 19, 21, 22, 25, 26", and the command for line 36 should be showing "The number of days that the Anchorage and NYC temperatures were the same was 1, this was on day 23." But when I run the script, both are showing a singular day (31). What am I doing wrong? Also if anyone has suggestions as to how I could make the code shorter that'd be great!
Note: We ran the following in class as a practice, which is what I've been using as a "guide" for this homework assignment:

Answers (1)

Marc Jakobi
Marc Jakobi on 11 Oct 2016
Edited: Marc Jakobi on 11 Oct 2016
In your first problem (Anchorage temp above NYC temp), you print x. But x is your looping index. So it always ends up as length(Temp_NYC) at the end of the loop.
It should be:
days = [];
c = 0;
for x=1:length(Temp_NYC)
if Temp_ACH(x)>TEMP_NYC(x)
c = c + 1;
days = [days; x];
end
end
fprintf('The number of days,... etc.')
fprintf('\n')
fprintf('%d\n', days)
The same goes for your second problem (Temp_ACH == Temp_NYC). I would suggest you use the same loop (just replace the > with ==).
I assume you are supposed to do it using a loop. If it doesn't matter how you solve it, here's a small tip: It is easier and faster to do it with logical indexing:
logical_index = Temp_NYC == Temp_ACH; % = "true" for days that had the same temperature and "false" for all that were different
days = find(logical_index); % The days: find() finds the "true" values and returns their indexes, which are equivalent to the days
num_days = length(days); % The number of days
P.S. Please don't send screenshots of your code. It is easier to analyse it if you copy and paste it into the forum and wrap it by selecting it and clicking on the {}Code button.

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!