0

I was trying to get k floating-point numbers that sum to 1. I found a code sample to do this:

row = rand(1, k)
row = row / sum(row)

Unfortunately, I get the following error:

Array indices must be positive integers or logical values

The problem is definitely with the sum function, because when I try the following:

row = rand(1, k)

% Sum of all of the numbers
a = 0

for index = 1:k
    a = a + row(index)
end

row = row / a

it does exactly what I expect.

Can someone explain why sum throws that error here (especially since the comments on the linked code sample implies that extremely similar code worked for them)? Is there some way that I can fix this?

  • Works fine on my end. Are you getting this for any/all `k`? Which MATLAB version? – tdy Apr 17 '21 at 09:09
  • 2
    My _guess_ is that you have a variable called `sum` in your workspace. This takes precedence over the function `sum`. – Edric Apr 17 '21 at 09:13

0 Answers0