Finding a number in an array less than 2

20 Ansichten (letzte 30 Tage)
Kyle Donk
Kyle Donk am 13 Jan. 2020
Beantwortet: Dominik Mattioli am 16 Jan. 2020
I'm trying to find a count of all the numbers in an array that are less than 2. I set up my code like this:
(y was already defined earlier)
%Determine the number of y-values less than the number 2.0.
%Display only the number of y-values less than the number 2.0.
for i=1:N
if y<2
disp('The number of values less than two is')
Yet whenever I try to run this, Matlab always says:
"Array indices must be positive integers or logical values."
Error in BasicSorts1 (line 35)
Why is Matlab telling me this?

Antworten (2)

Dominik Mattioli
Dominik Mattioli am 16 Jan. 2020
The error message is telling you that you are trying to index into a variable using an index that is not positive or a logical. It looks like you created a variable called 'sum' and are indexing into it using another variable called 'count', which is - for whatever reason - not a valid index.
As the other answered mentioned, your code is needlessly complicated, anyway. You can vectorize the operation of finding the number of y-values that are less than 2 like so:
clear sum % make sure you don't have a variable name overriding a function.
y = randn( 10000, 1 )
count = sum( y < 2 );
disp( ['The number of y-values < 2 is: ', num2str( count ) ] )
Or, if you need to use a for-loop, you need to index into the y-array and evaluate that element of y individually, not as a whole (that is what your code is doing):
count = 0;
for idx = 1:length( y )
if y( idx ) < 2
count = count + 1;
disp( ['The number of y-values < 2 is: ', num2str( count ) ] )

Bandar am 13 Jan. 2020
For this case, you may consider using vectorization. Try this code
A = [0 -1 2 3 2 5 -2];


Mehr zu Line Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by