Column Vector Containing the Row Sums of the Elements of A

6 ビュー (過去 30 日間)
Sophie Culhane
Sophie Culhane 2020 年 9 月 23 日
コメント済み: Ameer Hamza 2020 年 9 月 23 日
My task is to write a MATLAB function that takes as input a nonemty 2-dimensional array A and returns a column vector containing the row sums of the elements of A. I have a program written out, however it calculates and sum of all elements and puts them in a column vector. Please help me figure out how to only add the elements of one row and continue with the next. Here is what I have so far:
function RowSum = ex(A)
%
%
[NRows, NCols] = size(A);
RowSum = zeros(NRows, 1);
for row = 1: NRows
for col = 1: NCols
RowSum = RowSum + A(row, col);
end
end
Thank you in advance for the help.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 9 月 23 日
編集済み: Ameer Hamza 2020 年 9 月 23 日
Why not use the builtin function
M = rand(10, 5);
M_sum = sum(M, 2)
As for your current code, the correct is
function RowSum = ex(A)
%
%
[NRows, NCols] = size(A);
RowSum = zeros(NRows, 1);
for row = 1: NRows
for col = 1: NCols
RowSum(row) = RowSum(row) + A(row, col);
end
end
  3 件のコメント
Sophie Culhane
Sophie Culhane 2020 年 9 月 23 日
Thank you for your response.
Ameer Hamza
Ameer Hamza 2020 年 9 月 23 日
I am glad to be of help!

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

その他の回答 (2 件)

madhan ravi
madhan ravi 2020 年 9 月 23 日

Alan Stevens
Alan Stevens 2020 年 9 月 23 日
Matlab has the function "sum". Try help sum.

カテゴリ

Help Center および File ExchangeDesktop についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by