how to sum floating point elements of an array
29 views (last 30 days)
Hi I have an array which has floating point inputs. I need to sum all the elements to get a single value. The command 'sum' takes only integer inputs and throws error "??? Subscript indices must either be real positive integers or logicals" for double type inputs. Will appreciate any help.
Jan on 11 Sep 2012
Edited: Jan on 11 Sep 2012
While the command sum accepts arrays of floating point types also (see the documention!), this will fail if you overwrite the name "sum" by a variable:
clear sum % The initial status
sum(rand(1,5)) % works!
sum = 1:10; % Brrr, don't do it, although it is not a bug
sum(rand(1,5)) % Bug!
Check overwritten names by the command whos.
More Answers (1)
Oleg Komarov on 11 Sep 2012
"??? Subscript indices must either be real positive integers or logicals"
It means you're doing something:
a = 1:0.1:2;
b = rand(20,1);
You cannot select position 1.1, 1.2... of an array (or -1). The indexing of an array is done with whole positive integers 1, 2, 3...