14 views (last 30 days)

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
on 3 Feb 2017

Edited: Niels
on 3 Feb 2017

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.

Niels
on 3 Feb 2017

not calling any indices, you must have changed something in the code... if they run from 2:32 why did you change it to i=2:33?

i created VarName2 ... VarName33 and run the code without error.

what is the size of your matrices VarName2 and so one

Niels
on 3 Feb 2017

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

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/323136-how-to-sum-columns-of-multiple-matrices#comment_425643

⋮## Direct link to this comment

https://ch.mathworks.com/matlabcentral/answers/323136-how-to-sum-columns-of-multiple-matrices#comment_425643

Sign in to comment.