I have an array that includes a list of temps, and I am trying to count the temps less than 75. This is the code I used -
clc;
clear;
close all;
count=0;
a = [45, 56, 66, 78, 54, 67, 56, 88, 95, 93, 23, 56, 78, 45, 67, 56, 34, 67, 87, 64, 94, 57, 61, 24]; %16 below 75
for i = 1 : length(a)
if i < 75
count = count+1;
end
end
disp(count)
Not sure what is wrong. I am not able to get the desired output. Any help?

 Akzeptierte Antwort

Guillaume
Guillaume am 30 Aug. 2019
Bearbeitet: Guillaume am 30 Aug. 2019

0 Stimmen

Not sure what is wrong
You'll always going to get min(74, numel(a)) as a count, since you're comparing the index i instead of the value a(i) to 75.
Note that as usual in matlab, there's no need for a loop for this
count = nnz(A < 75)
%or
count = sum(A < 75)

2 Kommentare

Thank you. I tried the similar approach for other values. But that doesn't seem to work the same way.
clc;
clear workspace;
close all;
count = 0;
count2 = 0;
count3 = 0;
count4 =0;
a = [45, 56, 66, 78, 54, 67, 56, 88, 95, 93, 23, 56, 78, 45, 67, 56, 34, 67, 87, 64, 94, 57, 61, 24, 96, 98, 100, 109];
count = sum(a<75)
count2 = sum(75<a<95)
count3 = sum(95<a<105)
count4 = sum(a>105)
The variables "count2" and "count3" return output as 28, which is the array size. How do I rectify it?
Guillaume
Guillaume am 30 Aug. 2019
Well, yes, if you look at any matlab code (or for that matter code in other languages), they never use the syntax low<x<high. That's because it doesn't do what you want.
low < x < high first compares low to x and returns a logical vector of 0 and 1. it then compares this logical vector of 0 and 1 to high. So if high is greater than 1 the final result is just a vector of 1. Just as you get. The proper syntax is low < x & x < high.
So
count2 = sum(75<a & a<95);
%etc.
Note that numbered variables are universally a bad idea. Rather than embedding the index into the variable, use proper indexing:
count(1) = nnz(a < 75);
count(2) = nnz(75 < a & a < 95); %what about if a is 75?
count(3) = nnz(95 < a & a < 105); %or 95?
count(4) = nnz(a > 105); %or 105?
But even better, use histcounts:
count = histcounts(a, [-Inf, 75, 95, 105, Inf])

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2019a

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by