In: Computer Science
Matlab
Given an array of monthly rainfall that covers some number of years
(where each column is a month and each row is a year)
create a function YEARLY that prints the average rainfall for each year
For example, if the information below were to be stored in a 5x12 matrix RAIN...
J F M A M J J A S O N D 2003 1 2 1 2 1 2 1 2 1 2 1 2 2004 1 1 1 1 1 1 1 1 1 1 1 1 2005 2 2 2 2 2 2 2 2 2 2 2 2 2006 1 2 3 1 2 3 1 2 3 1 2 3 2007 5 1 2 4 3 3 5 1 2 4 3 3
Then the function YEARLY(RAIN) would print the result
average rainfall for year 1 is 1.500000 average rainfall for year 2 is 1.000000 average rainfall for year 3 is 2.000000 average rainfall for year 4 is 2.000000 average rainfall for year 5 is 3.000000
Note that only the rain amounts (not the labels) are stored in the input array (RAIN).
function [] = YEARLY(RAIN)
    x = 1;
    % iterating with seach row
    for row = RAIN.'
        % calculating average of row
        fprintf("average rainfall for year %d is %f\n",x,mean(row))
        x = x+1;
    end
end
% 
% RAIN = [
%     [1 2 1 2 1 2 1 2 1 2 1 2];
%     [1 1 1 1 1 1 1 1 1 1 1 1];
%     [2 2 2 2 2 2 2 2 2 2 2 2];
%     [1 2 3 1 2 3 1 2 3 1 2 3];
%     [5 1 2 4 3 3 5 1 2 4 3 3]
% ]
Code
Output