MATLAB Answers

Finding a number in an array less than 2

51 ビュー (過去 30 日間)
Kyle Donk
Kyle Donk 2020 年 1 月 13 日
回答済み: Dominik Mattioli 2020 年 1 月 16 日
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.
count=0;
N=length(y);
for i=1:N
if y<2
count=[y<2]
sum(count)
end
disp('The number of values less than two is')
disp(sum(count))
end
Yet whenever I try to run this, Matlab always says:
"Array indices must be positive integers or logical values."
Error in BasicSorts1 (line 35)
disp(sum(count))
Why is Matlab telling me this?

回答 (2 件)

Dominik Mattioli
Dominik Mattioli 2020 年 1 月 16 日
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;
end
end
disp( ['The number of y-values < 2 is: ', num2str( count ) ] )

Bandar
Bandar 2020 年 1 月 13 日
For this case, you may consider using vectorization. Try this code
A = [0 -1 2 3 2 5 -2];
A(A<2)

Community Treasure Hunt

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

Start Hunting!

Translated by