Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

I need help with a question: I have a matrix of 100 rows and 4 columns and im suppose to take the average of each column without using the mean function. The output is suppose to be a 1 row by 4 column matrix but i just get a single answer.

1 view (last 30 days)
if true
% code
end
function y = calc_average(y)
% input variable y is a matrix
% output variable x is vector
% x is average of columns of y
[rows, columns] = size(y);
n = numel(y);
avg = 0;
for k = 1:n
avg = avg + y(k);
end
y = avg/n;
end % function end statement

Answers (2)

Rafael Hernandez-Walls
Rafael Hernandez-Walls on 15 Nov 2017
If you can not use the MEAN function then you can use any other function! What if you use the SUM function in the following way! Assuming you have an A matrix:
A=rand(100,4);
p=sum(A)/100
I hope this suggestion will help you.
Regards
R.

Roger Stafford
Roger Stafford on 15 Nov 2017
If y is your matrix, and you must use a for-loop, do this:
n = size(y,2);
v = zeros(1,n);
for k = 1:n
v(k) = sum(y(:,k))/n;
end

Community Treasure Hunt

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

Start Hunting!