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.
0 件のコメント
採用された回答
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 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!