# Find average of an array for values > 0

조회 수: 5(최근 30일)
Cameron Bowyer 2021년 9월 12일
댓글: stozaki 2021년 9월 12일
find average of array only for values > 0 and print using for loop and for where there is data (ie more than 0 values in the data)
i) sum of values
IF DATA > 0****** --> this is my main issue im stuck with
for i = 1:length(data)
sum = sum + data(i)
end
fprintf("%.2f\n", sum)
ii) average
if length(data) > 0
average = sum/ length(data)
end
fprintf("%.3f\n", average)

댓글을 달려면 로그인하십시오.

### 답변(1개)

stozaki 2021년 9월 12일
Hi,
data = [1 2 10 -38 -7 2 8 10 -5 1 0 -5 37]; % example data
idx = find(data > 0); % Index of values greater than 0
result = mean(data(idx)); % average
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
stozaki 2021년 9월 12일
If you use for and if statements, you can do the following:
data = [1 2 10 -38 -7 2 8 10 -5 1 0 -5 37]; % example data
temp = 0; % initialize temp
count = 0; % initialize count
for N = 1:length(data)
if data(N) > 0
temp = data(N) + temp;
count = count + 1;
else
% nop
end
end
average = temp/count
average = 8.8750

댓글을 달려면 로그인하십시오.

R2021a

### Community Treasure Hunt

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

Start Hunting!