フィルターのクリア

How to find mean of a vector including only a specific range of elements

8 ビュー (過去 30 日間)
Sandie Nhatien Vu
Sandie Nhatien Vu 2016 年 8 月 5 日
編集済み: Sandie Nhatien Vu 2016 年 8 月 6 日
I am new with matlab, in advance sorry for my question. How can I find the mean of a vector that only takes elements between 15 and 25.
Ex.
I have a vector: v = [20 8 15 19 7 31]
What i want as output for this vector is (20+15+19)/3 = 18.
I know that the equation to use is:
sum(v)/length(v) = mean(v)
but i only want to include elements from 15:25 in any(!) vector.
My question: How can l write a program that computes and returns the mean, taking only the valid measurement (15-25)? This is regarding both vectorization and/loops
So far i have this code:
function averageRate = fermentationRate(vector)
averageRate = 0;
for k = 1:length(vector)
if (vector(k) < 25 && vector(k) > 15)
averageRate = (averageRate + vector(k));
end
end
That only tells the sum of the vector, i miss the dividing by length(vector). How can l add this?

採用された回答

James Tursa
James Tursa 2016 年 8 月 6 日
編集済み: James Tursa 2016 年 8 月 6 日
vector = whatever;
min_value = whatever; % 15 in your example
max_value = whatever; % 25 in your example
x = vector >= min_value & vector <= max_value; % or > and < instead of >= and <=
result = mean(vector(x));
  3 件のコメント
Stephen23
Stephen23 2016 年 8 月 6 日
This is a function, not a script, and you write it just like James Tursa showed you:
function out = fermentationRate(vec,lwr,upr)
out = mean(vec(lwr<vec & vec<upr));
end
and calling it:
>> fermentationRate([20.1, 19.3, 1.1, 18.2, 19.7, 121.1, 20.3, 20.0], 15, 25)
ans =
19.6
Sandie Nhatien Vu
Sandie Nhatien Vu 2016 年 8 月 6 日
編集済み: Sandie Nhatien Vu 2016 年 8 月 6 日
Thanks!! Now I finally got the usage of functions and scripts! - and the difference between.

サインインしてコメントする。

その他の回答 (1 件)

Star Strider
Star Strider 2016 年 8 月 6 日
This works:
v = [20 8 15 19 7 31]; % Vector
UL = 25; % Upper Limit
LL = 15; % Lower Limit
v_mean = sum(v((v >= LL) & (v <= UL))) ./ sum(((v >= LL) & (v <= UL))) % Mean Of ‘v’ Given Constraints
vm =
18
It is necessary to use ‘>=’ and ‘<=’ to get the result you want.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by