Find the average of a column without the use of commands.

I have a matrix that is [365,4] and I need to find the average of each column without the use of commands like mean or size. With the use of a for loop.

5 commentaires

What have you attempted?
I will correct myself by saying that I can use length. But I am running into the problem of using the length command to find the column amount. I am able to use size to find the average.
clear all; close all; clc
A = importdata('la_river.txt');
river = A.data;
R = length(river)
C = length(river(:,))
%%
[R,C] = size(river);
tot = 0.0;
total1 = 0.0;
total2 = 0.0;
total3 = 0.0;
total4 = 0.0;
for c=[1:C]
for r = [1:R]
tot = tot + river(r,c);
end
end
averagetot = tot/(C*R)
for r = [1:R]
total1 = total1 + river(r,1);
total2 = total2 + river(r,2);
total3 = total3 + river(r,3);
total4 = total4 + river(r,4);
end
averagetotal1 = total1/R
averagetotal2 = total2/R
averagetotal3 = total3/R
averagetotal4 = total4/R
Error using importdata
Unable to open file.
It is problem with importing data. What error you are getting?
Nevermind I am sorry, I realize I could use the size command for this code. But I don't have any errors in the code just needed some help with it.
Beware! length is a dangerous command/function that may not return what you intend -- it is defined as max(size(x)) and so returns either the number of elements in a row or column of any 2D array -- which would depend upon the array configuration. The 4x3 or 3x4 array will both return 4...

Connectez-vous pour commenter.

Réponses (1)

Sai
Sai le 18 Mai 2023
Modifié(e) : Sai le 18 Mai 2023
Hi Cappi,
I understand that you wanted to calculate the average of columns of a matrix without the usage of in-built commands.
Please find the following code snippet to do the same.
A = [1 2 3;4 5 6;7 8 9;10 11 12] %Consider the matrix for reference
A = 4×3
1 2 3 4 5 6 7 8 9 10 11 12
nRows = height(A);
nColumns = width(A);
avg = zeros(1,nColumns);
for i = 1:width(A)
C = A(:,i);
sum = 0;
for j = 1:nRows
sum = sum + C(j);
end
avg(i) = sum/nRows;
end
disp(avg)
5.5000 6.5000 7.5000

Catégories

Modifié(e) :

Sai
le 18 Mai 2023

Community Treasure Hunt

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

Start Hunting!

Translated by