Error using countOnes = sum(num); when trying to count how many zeros and ones are randomly generated.

18 views (last 30 days)
I have never used MATLAB before, and am trying to randomly generate 0s and 1s to calculate the probability of getting heads or tails on a coin. I used the code below, but keep getting an error on the line showing countOnes = sum(num); saying 'array indices must be positive integers or logical values.'. Anyone know what might be wrong? I clicked the explain error and it wasn't clear.
rng('shuffle'); %Generates a random number each time, instead of the same sequence
N = 1000; %Sets value of N to 1000 to simulate 1000 flips of the coin
num = randi([0,1], N, 1); %Generates a number 0 or 1
countOnes = sum(num);
countZeros = N - countOnes;
disp(['Number of 1s: ', num2str(countOnes)]);
Number of 1s: 518
disp(['Number of 0s: ', num2str(countZeros)]);
Number of 0s: 482

Answers (2)

Torsten
Torsten ongeveer 2 uur ago
Edited: Torsten ongeveer 2 uur ago
Works in R2025A (see above).
I suspect that somewhere in your code, you define a variable with name "sum". Rename it because it is in conflict with the MATLAB function.

Image Analyst
Image Analyst ongeveer 2 uur ago
This error message indicates that it thinks sum is an array in your program, so when you do
countOnes = sum(num);
where num can be values of zero or one, it's the zeros that are causing the problem since zero cannot be an index to an array. If it were a logical zero (false)
num = logical(randi([0,1], N, 1)); %Generates a boolean (logical) 0 or 1 (false or true)
then it would have not thrown the error, though since you defined sum somewhere else it would not be the count that you expect. It would have given you a vector of all the values in sum where num was true (1).
To fix, do not define sum, which overwrote the built-in sum() that you want. In general, never make functions or variables that have the same names as built-in MATLAB functions. For beginners experimenting with short scripts while learning MATLAB, it might not be a bad idea to put these lines at the start of your scripts just to get things back to an initial starting state
clear all % Delete any variables still hanging around from prior runs of this and other scripts.
close all % Close all existing figure windows.
clc; % Clear command window

Products


Release

R2025a

Community Treasure Hunt

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

Start Hunting!