cumulative average for each element

34 次查看(过去 30 天)
hey, i need to build a function who receives a vector and return the cumulative average for each element . for ex: vecMean([1 2 3 4])= [1 1.5 2 2.5].
the problem is that im reciving a row vector but sometimes i want to put column vec and recive a column also.
% the function calculates the cumulative average of elements in a vector.
% each element in the output vector is the average of this element and all
% previous elements in the input.
% the function gets a vector of numbers (=vecOfNum)
% and return output vector (=vecPrevMean),
% each element is the average of all previous elements.
function [vecPrevMean]= vecMean(vecOfNum)
count=1; %count the amount of elements in the vector
sumNum=0; %sum the elements
for i=1:length(vecOfNum);
if iscolumn(vecOfNum)==0
sumNum= sumNum+ vecOfNum(i);
vecPrevMean(i)=sumNum./count;
count=count+1;
elseif iscolumn(vecOfNum)==1
sumNum= sumNum+ vecOfNum(i);
vecPrevMean(i)=(sumNum./count)';
count=count+1;
end
end

采纳的回答

madhan ravi
madhan ravi 2018-11-26
编辑:madhan ravi 2018-11-26
no loops needed:
>> a=1:4
desired_result=cumsum(a)./(1:numel(a))
a =
1 2 3 4
desired_result =
1.0000 1.5000 2.0000 2.5000
>>

更多回答(1 个)

fakhri
fakhri 2022-11-30
hey,
Write a function called matMean that calculates the cumulative average of the rows or the columns of a matrix. Your function should get two input arguments: • First input argument: a matrix of numbers. • Second input argument: Type of cumulative average to calculate - can get one of two values: the number 1 for calculating the cumulative average of the rows of the matrix, or the number 2 for calculating the cumulative average of the columns of the matrix.
For this question you should write your own algorithm for calculating the cumulative averages of the arrays - do not use built-in statistical MATLAB functions such as: mean, sum, cumsum, etc
  1 个评论
DGM
DGM 2022-12-1
What part of this is an answer to the question?
What have you done other than pasting your assignment?
" For this question you should write your own algorithm"

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by