1

I have a transfer function that I am trying to use to filter acceleration data.

So far I have been able to use lsim with a sin wave over about 10 seconds and I'm getting the result I expect. However, I cannot work how to get data to the function in real time.

To clarify, every 0.1 seconds I am receiving an acceleration value from an external program. I need to filter the values to remove high frequency variations in the data. I need this to occur for each data point I receive as I then use the current filtered acceleration value into additional processing steps.

How do I use the transfer function in continuously and update the output value each time new data is received?

Steve
  • 9,335
  • 10
  • 49
  • 81

1 Answers1

2

This is an example of how to do this with filter:

filter_state = []; % start with empty filter history
while not_stopped()
    x = get_one_input_sample();
    [y, filter_state] = filter(B, A, x, filter_state);
    process_one_output_sample(y);
end;

Note that you need to use the extended form of filter, in which you pass the history of the filter from one iteration to the next using the variable filter_state. The B and A are the coefficients of your discrete filter. If your filter is continuous, you need to transform it to a discrete filter first using c2d or so. Note that if your filter is very complex, you might need to split up the filtering in several steps (e.g. one second-order-stage per filter) to avoid numerical problems.

Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62
  • You've got get_one_input_sample, I'm assuming you are pulling the data from elsewhere. Can it be told what the data is *from* the external program? More like a push to matlab, rather than a pull. Or, is it best to publish the current value on something like a UDP port and get it from Matlab? – Steve Oct 15 '13 at 00:34
  • I guess it can be done either by pushing or pulling the data, this will totally depend on how you interface you hardware with matlab. You might want to ask a separate question for that. For the filtering part, this does not matter, it is always one sample in, one sample out, while making sure to pass the history of the filter to the next iteration. – Bas Swinckels Oct 15 '13 at 08:53
  • Ok, I have an idea to get the data, but what format does it need to be in? Can it just be a number? For example, my data I receive every 0.1 seconds is: 0.3,0,0.01,0.1,0.4,0.6,0.6 etc. Can I just do filter(B,A,0.3,filter_state), then filter(B,A,0,filter_state) etc? – Steve Oct 20 '13 at 08:14
  • Yes, that is the idea. When working with off-line data, you typically want to filter on long vectors, since that is faster. In real-time applications, you only have one sample available per iteration, so that is what you use. The `filter` function should work without problems handling one sample at a time, as long as you handle the filter state correctly. – Bas Swinckels Oct 20 '13 at 15:38