필터 지우기
필터 지우기

How to use 'if' statement to pick up 3 to 4 values from the data that nearest to the mean?

조회 수: 2 (최근 30일)
Hi, this question is on the same project I've been working on 10 Oct 2016 at 7:35.
I have 24 values of data and a mean value. I've been working to get 3 to 4 value from the last half of the data that are nearest to the mean by using 'if' statement. I know 'if' statement can be like these... [ if any(statement) ] or [ if all(statement) ] .
So, how can I code it to pick up 3 to 4 values from the data that nearest to the mean? Here is my code from the latest question.
function [Consistency,limit] = detection(x,y)
H = x;
G = H(y:24,:);
limit = mean(H(1:24,:));
if all(G > limit)
S = std(G);
Consistency = S;
else
Consistency = inf;
end
Hope anyone can guide me. Thanks.

채택된 답변

Walter Roberson
Walter Roberson 2016년 10월 16일
function [Consistency,limit] = detection(x,y)
H = x;
G = H(y:24,:);
limit = mean(H(1:24,:));
vals4 = zeros(1,4);
bestdiff = inf(1,4);
bestvals = inf(1,4);
for r = 1 : size(G,1)
for c = 1 : size(G,2)
thisval = G(r,c);
thisdiff = abs(thisval - limit);
if thisdiff < bestdiff(1)
bestdiff = [thisdiff, bestdiff(1), bestdiff(2), bestdiff(3)];
bestvals = [thisval, bestvals(1), bestvals(2), bestvals(3)];
elseif thisdiff < bestdiff(2)
bestdiff = [bestdiff(1), thisdiff, bestdiff(2), bestdiff(3)];
bestvals = [bestvals(1), thisval, bestvals(2), bestvals(3)];
elseif thisdiff < bestdiff(3)
bestdiff = [bestdiff(1), bestdiff(2), thisdiff, bestdiff(3)];
bestvals = [bestvals(1), bestvals(2), thisval, bestvals(3)];
elseif thisdiff < bestdiff(4)
bestdiff = [bestdiff(1), bestdiff(2), bestdiff(3), thisdiff];
bestvals = [bestvals(1), bestvals(2), bestvals(3), thisval];
end
end
end
Now bestvals are the 4 values that are closest to the mean.
I would certainly not code it this way for myself, but you specifically asked to use if, so this is the version that uses if.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by