How to sum columns of multiple matrices?

조회 수: 2 (최근 30일)
Sashank Jammalamadaka
Sashank Jammalamadaka 2017년 2월 2일
댓글: Sashank Jammalamadaka 2017년 2월 3일
I have 32 column matrices of different names to be added separately. Is it possible to write a loop to do it instead of writing Sum1 = sum(VarName2)... and so on for 32 matrices?
I have matrices named VarName2, VarName3, ..., VarName33. I tried using the following loop;
for i = 1:32
sum(i)= sum(VarName(i));
end
and it returned the error "Undefined function or variable 'VarName'". So, needed help with this.

채택된 답변

Niels
Niels 2017년 2월 3일
편집: Niels 2017년 2월 3일
final_sum=0;
for i= 1:32 % splitted command as string: sum(VarNamei)
final_sum=final_sum + evalin('base', ['sum(VarName', num2str(i) ,')']);
end
the sum of all vectors (if sum is used on a matrix, the result will be a row vector) ...
just tell me if it works, i had no problem using it.
  댓글 수: 3
Niels
Niels 2017년 2월 3일
chnged the code so that final_sum is a 32x1 vector where final_sum(i) contains the sum of VarName2+...VarNamei
final_sum = zeros(32,1);
final_sum(1) = VarName2;
for i= 3:33 % splitted command as string: sum(VarNamei)
final_sum(i-1) = final_sum(i-2) + evalin('base', ['sum(VarName', num2str(i) ,')']);
end
Sashank Jammalamadaka
Sashank Jammalamadaka 2017년 2월 3일
Thank You, it worked!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by