How to loop through array?
4 次查看(过去 30 天)
显示 更早的评论
function ans = stable(mass):
for mass(k) in mass(:):
average
= mean(mass(k:k+1080);
delta = abs(average - mass(k)) % I am totally lost
as to how to make this loop over the entire array
if (delta <= 0.0005*
mean) = 1
return mass(k+1080)
else % bool = 0
continue
So, I know this is a complete mess, but hear me out.
I want to build a function that takes in 'mass', which is an array of 10,000 numbers.
I want this to loop over the entire array:
Take first element of mass:
calculate mean of next 1080 elements
calculate delta = abs(mean - element)
if delta <= 0.0005 * mean, return True (1), return 1080 + 1st element (later, this would return 1080 + kth element)
I'm very new to Matlab. I'm only familiar with python which is what my code very vaguely resembles.
Please help.
1 个评论
dpb
2016-7-15
Your description is very hazy...you say want to loop over full array, but only want the mean of array(2:1081). So what do you do with the rest of the array? Or do you mean you want a running average of 1080 elements? If the latter, do you want the length of the output array to be length(input)-1080 or length(input) or what?
How about an illustration with small sample size of say 10 or so elements in the array and 3 or 4 for 1080 and show us what you'd get for a sample dataset and how you'd calculate it on paper.
回答(1 个)
Guillaume
2016-7-15
1. You really need to learn a modicum of matlab. The code you've posted is in no way valid matlab syntax
2. Do not use ans as a variable name. It's a special variable that matlab may modify.
3. Since R2016a, you can use movmean to calculate the moving average. Prior to that an easy way was to use a convolution. So, if I understood correctly
function [isstable, filteredmass] = stable(mass)
runningmean = movmean(mass, 1080, 'Endpoints', 'discard'); %if r2016a or later
%otherwise
%runningmean = conv(mass, ones(1, 1080)/1080, 'valid');
isstable = abs(mass(1:numel(runningmean)) - runningmean) < 0.0005 * runningmean;
filteredmass = mass(1080:end);
filteredmass = filteredmass(isstable); %I think this may be what you meant
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!