How to get the sum of each row in a matrix.

15 views (last 30 days)
The last line in this sums each row in the matrix, is their a way to tell it to do that with out having to type out a sum for each row of the matrix.
carbon=12;
hydrogen=1;
oxygen=16;
Methanol=[1 4 1];
ethanol=[2 6 1];
propanol=[3 8 1];
butanol=[4 10 1];
pentanol=[5 12 1];
atomic_weights=[carbon hydrogen oxygen];
mixer=[Methanol; ethanol; propanol; butanol; pentanol];
unsumed=[mixer.*atomic_weights];
question_5=[sum(unsumed(1,:)),sum(unsumed(2,:)),sum(unsumed(3,:)),sum(unsumed(4,:)),sum(unsumed(5,:))]

Accepted Answer

Voss
Voss on 26 Feb 2024
% sum over 2nd dimension
question_5 = sum(unsumed,2)
  1 Comment
Voss
Voss on 26 Feb 2024
That makes question_5 a column vector. Transpose it to exactly match the row-vector result you had before:
% sum over 2nd dimension
question_5 = sum(unsumed,2).'

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!