How to use 'if' statement to pick up 3 to 4 values from the data that nearest to the mean?
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Walter Roberson
on 16 Oct 2016
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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!