How do I merge two columns in a Matrix in Matlab?

8 Ansichten (letzte 30 Tage)
Jose Coronado
Jose Coronado am 2 Sep. 2015
Kommentiert: Star Strider am 2 Sep. 2015
I have a n x (n+1) matrix and I want to add the row elements of only the third and second column in order to arrive to a n x n matrix. Something like:
1 2 3;
4 5 6;
7 8 9
and end up with:
1 5;
4 11;
7 17
Thanks for the help!

Akzeptierte Antwort

Star Strider
Star Strider am 2 Sep. 2015
Use the sum function:
A = [1 2 3;
4 5 6;
7 8 9];
B = [A(:,1) sum(A(:,2:3),2)]
B =
1 5
4 11
7 17
  2 Kommentare
Jose Coronado
Jose Coronado am 2 Sep. 2015
Thank you!
What if I have n columns before the ones that I want to add? or m columns after the ones i want to add?
Star Strider
Star Strider am 2 Sep. 2015
My pleasure!
Select the columns to exclude before and after, and sum the ones you want. For example, if ‘A’ has 10 columns and you want to sum 5, 6 and 7, this would work:
B = [A(:,1:4) sum(A(:,5:7),2) A(:,8:10)]
Remember to use the square brackets to concatenate the elements of ‘A’ to create ‘B’.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by