How to create a for loop to do sums of every values in the whole row?

2 ビュー (過去 30 日間)
Darkhan Kenestegi
Darkhan Kenestegi 2016 年 12 月 15 日
コメント済み: Darkhan Kenestegi 2016 年 12 月 15 日
I have a matrix lets say a=[1,2,3;9,8,7;4,5,6]
I want to create a loop that will sum each row, like:
sum(a(1,:));
The problem is I want it to be repeated for every row.
Will appreciate any help! Cheers!

採用された回答

KSSV
KSSV 2016 年 12 月 15 日
a=[1,2,3;9,8,7;4,5,6] ;
b = zeros(size(a,2),1) ;
for i = 1:size(a,2)
b(i) = sum(a(i,:)) ;
end
b
b1 = sum(a,2)
  2 件のコメント
Darkhan Kenestegi
Darkhan Kenestegi 2016 年 12 月 15 日
Thank you! But I get an error in my original code "index exceeds matrix dimensions". In my case I have 15 rows and 186 columns. Maybe My initial example was easier due to 3x3 matrix, but now we have irregular matrix.
Darkhan Kenestegi
Darkhan Kenestegi 2016 年 12 月 15 日
Oh it's fine! I figured it out! I just changed conditions to for i = 1:size(a,1)
And that seems to solve the problem.
Thank you for your help.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by