Error using countOnes = sum(num); when trying to count how many zeros and ones are randomly generated.
18 views (last 30 days)
Show older comments
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)]);
disp(['Number of 0s: ', num2str(countZeros)]);
1 Comment
Stephen23
43 minuten ago
Delete the variable named sum that you created in your workspace. Then it will work.
Answers (2)
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
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!