Storing input variables x in a persistent variable called buffer

4 次查看(过去 30 天)
Hi there,
I am trying yo create a function which input x as a scalar and stores in a persistent variable called buffer. and it calculates the average of input every time I input a new x. The function uses a “buffer” to hold previous inputs, and the buffer can hold a maximum of 25 inputs. I want to know how I can add input to the buffer which is a persistent variable and see the inputs stored in the buffer? Thanks

采纳的回答

Jan
Jan 2015-5-2
The description sounds clean and clear enough to allow for a straight forward implementation. What should happen if the function is called the 26th time? Should the buffer wrap around in a first-in-first-out style?
What have you tried so far? Usually it is more efficient to posr, what you have written and ask specific questions. But it is saturday and I try it:
function YourAccumulator(x)
persistent buffer bufferIndex
if isempty(buffer) % Called the first time
bufferIndex = 0;
end
bufferIndex = bufferIndex + 1
buffer(bufferIndex) = x;
if bufferIndex == 25
bufferIndex = 1;
end
M = mean(buffer);
disp(M);
The mod() operator would help to remove the if part.
  1 个评论
yashar khatib shahidi
编辑:yashar khatib shahidi 2015-5-4
Hi, Thanks for your reply. I have created a function that approximates pi and Instead of going to infinity, the function stops at the smallest k for which the approximation differs from pi (i.e., the value returned MATLAB’s built-in function) by no more than the positive scalar delta, which is the only input argument. The first output of the function is the approximate value of π, while the second is k. There is something wrong with this when I enter any delta it goes into infinite loop. Here is my code:
function [approx, k] = approximate_pi(delta)
approx = sqrt(12);
k = 0;
while abs(approx - pi) > 1e-2*delta
k = k + 1;
approx = approx + sqrt(12)*(((-3)^(-k))/(2*k+1))
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Measurements and Spatial Audio 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by