Running average using for loops
16 ビュー (過去 30 日間)
古いコメントを表示
I am tasked with writing a code which calculating a running average using a for loop on any desired file with any number of 'n' - samples and plot it against the raw data. This is how far I've managed to get, it runs with samples of 1 but everything above that it throws an error on lines 3 and 22. Any guidance is greatly appreciated.
edit: I've attached the file of the data I'm attempting to average and added the error messages I recieved.
%number of samples
n = input('enter sample amount: ');
%file of data
s = input('enter file name: ','s');
%function name
b = run_avg(n,s);
a = load(s);
%plot of raw data against the averaged data
plot(1:length(b),b, 1:length(a),a);
function avg = run_avg(n,s)
a = load(s);
x = length(a);
b = zeros(1,x);
%for loop to filter data of uploaded file.
for i = 1:x
%for the beginning of data set
if i < n-2
for j= i:i+(n-1)
b(i) = b(i) + a(j);
end
end
if i > n-2
for j = i - (n-1)/2 : i + (n-1)/2
b(i) = b(i) + a(j);
end
end
end
avg = b/n;
end
%error message
Array indices must be positive integers or logical values.
Error in run_av6>run_avg (line 22)
b(i) = b(i) + a(j);
Error in run_av6 (line 3)
b = run_avg(n,s);
5 件のコメント
Rik
2019 年 3 月 14 日
In my first comment I linked to the Wikipedia page for minimal working example. So you need to provide a resonable value for n, as well as a reasonable value for s. Once you have provided those we can help you further.
As for you code itself, it is still unclear to me what you are doing. Try to explain why you have two inner loops separated by some logic. Why are you using those logical statements? What do they mean? Try to write a comment for each line.
The way I would write a window average is either with a convolution, or with a single loop.
採用された回答
Rik
2019 年 3 月 13 日
I guess boldly:
If you want a sliding window average, you can use a convolution:
data=magic(8);data=data(:);%generate some data
x=linspace(0,1,numel(data));%generate some x-values
%create the filter kernel
window_kernel=[1 1 1 1];window_kernel=window_kernel/sum(window_kernel);
%apply convolution
new_data=conv(data,window_kernel,'same');
%plot
figure(1),clf(1)
plot(x,data,'r','DisplayName','raw')
hold on
plot(x,new_data,'b','DisplayName','filtered')
hold off
legend
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!