MATLAB Answers

How to get a script to only give me the number of elements less than 2?

3 views (last 30 days)
Kyle Donk
Kyle Donk on 9 Jan 2020
Commented: David Hill on 9 Jan 2020
I have a script in which y equals 100 various numbers. I was able to sort the numbers in order from least to greatest, but I need the script to give me the amount of numbers that are less than 2. How would I go about doing this?

  0 Comments

Sign in to comment.

Accepted Answer

David Hill
David Hill on 9 Jan 2020
nnz(y<2);

  4 Comments

Show 1 older comment
David Hill
David Hill on 9 Jan 2020
I obviously don't understand, but if you have an array, y:
y=randi(10,1,100);
nnz(y<2)%gives you all values of y < 2 (this will not change unless y changes.
Kyle Donk
Kyle Donk on 9 Jan 2020
But it would make sense for y to change each time I run the script, right? Because if y is a set of 100 random numbers, those numbers would change each time.
David Hill
David Hill on 9 Jan 2020
But each time you run the script,
z=nnz(y<2);
will provide you the number of values of y <2

Sign in to comment.

More Answers (1)

Meg Noah
Meg Noah on 9 Jan 2020
Here are random numbers as an example. It plots all the values in blue, finds indices for values less than 2, and plots those values in red.
x = 1:100;
y = 20*rand(100,1)-10;
ind = find(y < 2);
figure()
plot(x,y,'.b');
hold on
plot(x(ind),y(ind),'.r');

  2 Comments

Kyle Donk
Kyle Donk on 9 Jan 2020
This is good, but I need the script to only display how many numbers are less than two. I am not allowed to count the numbers manually.
So if there are five numbers less than two, I need the script to give me "5".
Meg Noah
Meg Noah on 9 Jan 2020
to display on the console, just use num2str or fprintf
num2str(numel(ind))
fprintf(1,'There are %d values less than 2\n',numel(ind))

Sign in to comment.

Sign in to answer this question.

Tags


Translated by