Determine the number of y-values less than the number 2.0

조회 수: 5 (최근 30일)
Benjamin Trivers
Benjamin Trivers 2020년 1월 16일
답변: Dominik Mattioli 2020년 1월 16일
y = 2.5 + 1 * randn(100,1)
sum=0;
N=length(y);
for i = 1 : N
sum= sum + y(i);
end
average=sum/N;
fprintf('the average of this list is %f\n', average)
%%
count=0;
N=length(y);
for y=1:N
if y<2
count=[y<2]
sum(count)
end
disp('The number of values less than two is')
disp(sum(count))
end
above is my code. I can't seem to get the count of values less than 2. need help
  댓글 수: 1
Star Strider
Star Strider 2020년 1월 16일
The problem could be that using a variable named ‘sum’ overshadows the sum function.
It is not obvious what your code is supposed to do.

댓글을 달려면 로그인하십시오.

답변 (2개)

David Hill
David Hill 2020년 1월 16일
y = 2.5 + randn(100,1);
a=mean(y);
fprintf('the average of this list is %f\n', a);
t=nnz(y<2);
fprintf('The number of values less than two is %d\n', t);

Dominik Mattioli
Dominik Mattioli 2020년 1월 16일
First, your variable 'sum' in your first for-loop is problematic because it is overwriting a built-in MATLAB function called 'sum', rendering it unusable.
A few problems in the second for-loop - here's psuedo code of what you're doing.
y = array_of_random_numbers
For y equal to 1 through the length of y (this reassigns your variable array y to an integer, losing all information):
if y < 2, which is only true for your first iteration:
create a 1x1 logical array detailing whether my iterator is less than 2 (only true for your first iteration)
sum this 1x1 logical array
display the sum of the 1x1 array (in this case, you're only referring to the value of 'count' from your first iteration for all iterations).
Try this instead:
y = 2.5 + 1 * randn(100,1)
y_sum = sum( y, 1 ); % Rename this variable.
N = length( y );
for index = 1:N
y_sum = y_sum + y( index );
end
average = y_sum / N;
fprintf( 'The average of this list is: %f\n', average )
%%
count = 0;
N = length( y );
for iter = 1:N
if y( iter ) < 2
count = count + 1;
end
disp( ['The number of values less than two is: ', num2str( count )] )
end
Alternatively, you could vectorize your code to make it more efficient and cleaner-looking:
y = 2.5 + 1 * randn(100,1)
% y_sum= sum( y, 1 ); % Your first for-loop is unneccessary if you use the built-in function.
average = mean( y )
fprintf('the average of this list is %f\n', average)
%%
count = sum( y < 2, 1 );
disp( ['The number of values less than two is: ', num2str( count )] )

카테고리

Help CenterFile Exchange에서 Point Cloud Processing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by