フィルターのクリア

taking the sum and average of a matrix using for loops while excluding two elements?

2 ビュー (過去 30 日間)
As an example I am taking the sum and average of a matrix x = [10 7 7 6 7 7 8 5 7 7]
I want to exclude the values 10 and 5 and try doing it as done in my code, but it doesn't seem to take the average correctly or the sum. Is there a way to fix my code to make it do this?
theSum = 0;
for k = 1 : length(x);
if k>5 && k<10
theSum = theSum + x(k);
end
end
avg=theSum/8

採用された回答

Star Strider
Star Strider 2018 年 6 月 9 日
One approach:
x = [10 7 7 6 7 7 8 5 7 7];
newx = x(x~=10 & x~=5)
theSum = sum(newx)
avg = theSum/length(x)
I used a separate vector ‘newx’ to illustrate the approach. You can use x(x~=10 & x~=5) directly in the argument to sum without creating the vector if you prefer.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by