variables - moving average function matlab (without the use of a for loop) -
i trying complete matlab assignment project following question:
write function called moving_average takes scalar called x input argument , returns scalar. function uses “buffer” hold previous inputs, , buffer can hold maximum of 25 inputs. specifically, function must save recent 25 inputs in vector (the buffer). each time function called, copies input argument element of buffer. if there 25 inputs stored in buffer, discards oldest element , saves current 1 in buffer. after has stored input in buffer, returns mean of elements in buffer.
the solution provide following:
function ma = moving_average (x) persistent buffer; if isempty(buffer) buffer = x; ma = mean(x); else buffer = [buffer x]; if numel(buffer) <= 25 ma = mean(buffer); else ma = mean([buffer(end-24) buffer(end)]); end end
according auto grader function performs correctly when values 1-50 passing consecutively, fails when values of noisy sine wave passing consecutively (which have been informed might due sort of round off error).
i grateful if of provide me hints regarding possible error steps in code (appended above).
thank in advance
you averageing last , 25th last.
use:
ma = mean(buffer(end-24:end));
comment on code: perform well, if function not called often. but, if function called lot of times, buffer
will bigger , bigger. possible memory leak. should consider keeping 25 values in buffer:
if length(buffer) > 25 buffer = buffer(end-24:end); end
Comments
Post a Comment