How can I sum the elements in a vector row without using the sum function or any form of loops?

10 ビュー (過去 30 日間)
How can I sum the elements in a vector row without using the sum function or any form of loops?

回答 (2 件)

per isakson
per isakson 2020 年 3 月 26 日
編集済み: per isakson 2020 年 3 月 26 日
This is one way
>> vec = (1:12);
>> vec*ones(12,1) % replace '12' by length(vec)
ans =
78
and check if that's the correct result
>> sum(vec)
ans =
78

Peng Li
Peng Li 2020 年 3 月 26 日
I don't quite understand your point about not using the function sum. But it is definitely possible to not use any form of loop.
suppose A is a matrix. sum(A) or sum(A, 1) calculates the sum along the first dimension (row). It gives the sum of each column, thus resulting you a row vector.
sum(A, 2) calculates the sum along the second dimension (column), thus throwing you a column vector with each element the sum of each row.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by