필터 지우기
필터 지우기

sum all columns in a matrix

조회 수: 9 (최근 30일)
Ariela Glikman
Ariela Glikman 2018년 12월 8일
댓글: Maneet Kaur Bagga 2022년 7월 5일
hi,
i want to sum all the columns of some matrix.
but without using a loop or the sum function.
for ex:
for the matrix [1 3 2; 4 4 8]
i will recive [5 7 10]

답변 (2개)

James Tursa
James Tursa 2018년 12월 8일
Hint: Look at matrix multiplication.

Maneet Kaur Bagga
Maneet Kaur Bagga 2022년 7월 5일
As per my understanding you want to get the sum of the matrix coloumn wise so you can use the MATLAB sum function. All the MATLAB functions by default work on coloumn so you get the sum directly. You can refer to the code below. Hope it helps!
x = [1 3 2; 4 4 8]
x = 2×3
1 3 2 4 4 8
sum(x)
ans = 1×3
5 7 10
  댓글 수: 2
DGM
DGM 2022년 7월 5일
In any practical scenario, using sum() would be perfectly sensible, but OP was working around contrived limitations -- no loops and no sum().
Maneet Kaur Bagga
Maneet Kaur Bagga 2022년 7월 5일
Thanks for correcting DGM,
You can refer to the below code as a solution.
x1 = [1 2 3; 4 5 6; 7 8 9];
all =(x1);
sumcol=0;
for i=1:length(all)
sumcol = 0;
for j = 1:length(all)
sumcol = sumcol + all(j,i);
end
fprintf("%d ",sumcol);
end
12 15 18

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by