Find average of an array for values > 0

27 views (last 30 days)
Cameron Bowyer
Cameron Bowyer on 12 Sep 2021
Commented: stozaki on 12 Sep 2021
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)

Answers (1)

stozaki
stozaki on 12 Sep 2021
Hi,
What about the following processing?
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 Comments
Cameron Bowyer
Cameron Bowyer on 12 Sep 2021
Thank you very much for the reply. I have to use for and if statements to come up with the answer for average I, umfortunately, cannot just do "mean(data)".
i really like the idea of the idx = find(data > 0); though and I will try that in my code now.
instead of calling this "idx" can i name it something like "data > 0" as it might be more appropriate?
stozaki
stozaki on 12 Sep 2021
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

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!