Tudor Plugaru
Tudor Plugaru

Reputation: 7

How to can I count the number of ones?

The problem is: In a class of 26 students, a test with 10 questions is given. The students answer the question by tossing a coin. I have to find out how many students have two or less answers correct. This is the program that I wrote, but I'm not sure about it ... is it good?

correct=0;
students=0;
for i=1:26
    for j=1:10
        answ=ceil(rand);
        if answ==1
            correct=correct+1;
            if correct==2
                students=students+1;
            end
        end
    end
end
disp(students)

Upvotes: 0

Views: 74

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112659

It's neater, faster to run, and more readable if you do it vectorized:

answers = round(rand(10,26)); % 10x26 matrix of 0 / 1 values
correct = sum(answers); % sum along each column
students = sum(correct<=2) % how many values of correct are 2 or less

By the way, from your code it appears you want to know how many students have 2 or more correct answers (not 2 or less as you state). In that case change last line to

students = sum(correct>=2) % how many values of correct are 2 or more

Upvotes: 5

jkshah
jkshah

Reputation: 11703

Slight modification to your code:

correct=0;
students=0;
for i=1:26
    for j=1:10
        answ=round(rand);    % Use round instead of ceil
        if (answ==1)
          correct=correct+1;
          if correct==2
              students=students+1;
              break;
          end
        end
    end
    correct=0;   % Was missing in original code
end
disp(students)

Additional Note:

  1. Try testing code for correct ans 5 as this will have more chances of variation to result because of uniform distribution of random number. Most of the students will get at-least 2 correct ans assuming equal probability, which is not the practical case.

  2. Try maintaining habit of proper indentation. It will be more readable and less prone to errors.

Upvotes: 0

Vuwox
Vuwox

Reputation: 2359

Just like this : (You have to reset correct counter for every student, and some end aren't at the right place.)

correct = 0;
students = 0;

for i = 1:26
  for j = 1:10
    answ = ceil(rand);
    if(answ==1)
      correct = correct + 1;
    end
  end

  if(correct < 2)
    students = students + 1;
  end

  correct= 0;
end

EdIT

Sorry, I didn't saw the less in your sentense, so I change the > for <

Upvotes: 0

Related Questions