How to loop through array?

조회 수: 4 (최근 30일)
pudje
pudje 2016년 7월 15일
편집: pudje 2016년 7월 20일
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
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
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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by