Find average of an array for values > 0
27 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
回答(1 个)
stozaki
2021-9-12
2 个评论
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!