How to find the sum and average of an array w/o sum and mean command using fprintf?

  • 1988 9.2 5.4 5.6 1.2 2.2 0.1 0.0 0.0 0.1 0.0 0.4 2.3
  • 1989 12.3 3.4 2.1 1.9 1.2 0.5 0.1 0.0 0.3 0.3 0.5 2.1
  • 1990 10.2 6.7 3.3 1.3 1.1 0.2 0.2 0.0 0.1 0.2 0.3 1.9
  • 1991 9.0 2.3 4.8 0.7 0.6 1.1 0.0 0.0 0.0 0.1 0.6 3.4
^The array above is displaying the year on the left, and the rainfall each month for that year on right
I need to create a 2 column table with the year on the left, and the total rainfall that year on the right. Then I need to create another 2 column table with the months on left, and the average rainfall of each month on the right. And i have to do this using fprintf without any matlab built in commands. Right now I have no clue how to do this. Any hints?

답변 (1개)

WIthout built-in command sum and mean? What the point to use Matlab then ?
Anyway, you just need to implement some basic algorithm in your case.
A = [1988 9.2 5.4 5.6 1.2 2.2 0.1 0.0 0.0 0.1 0.0 0.4 2.3
1989 12.3 3.4 2.1 1.9 1.2 0.5 0.1 0.0 0.3 0.3 0.5 2.1
1990 10.2 6.7 3.3 1.3 1.1 0.2 0.2 0.0 0.1 0.2 0.3 1.9
1991 9.0 2.3 4.8 0.7 0.6 1.1 0.0 0.0 0.0 0.1 0.6 3.4];
% init matrix with zeros
MySum = zeros(size(A,1),2);
MyMean = zeros(size(A,1),2);
% first column is a copy of the year
MySum(:,1) = A(:,1);
MyMean(:,1) = A(:,1);
% double loop to calculate sum and mean.
for i = 1:size(A,1)
for j = 2:size(A,2)
MySum(i,2)= MySum(i,2) + A(i,j);
end
MyMean(i,2) = MySum(i,2)/(size(A,2)-1);
end

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2014년 11월 9일

답변:

2014년 11월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by