how to sum floating point elements of an array

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.
Thanks, Subrat

2 件のコメント

Andrei Bobrov
Andrei Bobrov 2012 年 9 月 11 日
a = rand(8,1) % the initial array
out = sum(a)
Yoheena Kotikawatte
Yoheena Kotikawatte 2018 年 3 月 24 日
Hi! How do i make this work:
k = 25;
v=[1;0];
pvalues=[0:.01:1];
for i1=1:length(pvalues) p=pvalues(i1); A =[(2-p) (0.25*p); p (1.25-0.25*p)]; numbbacteria=(A^k)*v; y(p) = sum(numbbacteria); end
plot(pvalues,y) ylabel('Total number of bacteria'); xlabel('Probability that a bacteria will switch states');
because I get the eror: Subscript indices must either be real positive integers or logicals.
Error in p_file (line 8) y(p) = sum(numbbacteria);
I do understand the eror but how do i make it work with decimals?

サインインしてコメントする。

 採用された回答

Jan
Jan 2012 年 9 月 11 日
編集済み: Jan 2012 年 9 月 11 日

12 投票

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.

6 件のコメント

Oleg Komarov
Oleg Komarov 2012 年 9 月 11 日
Haven't thought of that, but it makes very much sense now.
Subrat kumar sahoo
Subrat kumar sahoo 2012 年 9 月 11 日
Thanks Jan. thats precisely was my mistake, I already had a variable in the name "sum." Thanks for the help
Karttikeya Mangalam
Karttikeya Mangalam 2016 年 6 月 22 日
Thanks! Still saving an hour in 2016 :)
Anu MAngla
Anu MAngla 2016 年 10 月 13 日
Thanks Jan Simon.. I was unable to find my mistake from a month and i haven't thought of this. Thanks for the help
Khushi Bhatti
Khushi Bhatti 2019 年 3 月 12 日
Thank you so much Jan! it took me two hours to find my mistake. you just solved it in a second. very helpful
SWATI BHARGAVA
SWATI BHARGAVA 2019 年 12 月 2 日
Saved me too! Thank you!! Glad came across this solution!

サインインしてコメントする。

その他の回答 (1 件)

Oleg Komarov
Oleg Komarov 2012 年 9 月 11 日

0 投票

"??? 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);
b(a)
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...

1 件のコメント

Subrat kumar sahoo
Subrat kumar sahoo 2012 年 9 月 11 日
Thanks Oleg for explaining the error

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by