Assign index to a matrix?

Hello! I have matrices E1, E2, E3...E50 of same dimension. I want to make a loop to add them all instead of manually putting E1+E2+E3... I think I will need to assign E1=some index and so on. How to put a loop around these matrices? (E1, E2, E3 are just the names and not the indices) I want something like following,
% code
E_1=2
E_2=3
E_3=9
....E_50=8
for k=1:50
sum(E_k)
end

4 Comments

Perhaps the real question is why are all these matrices separate in the first place. If the data had all been stored in the same matrix, you wouldn't have this problem of trying to create workarounds.
Yes,you are perfectly right. But my matrices are formed in the following way. Is there a way I can put indices to E1,E2..?
% code
E1(1,j)=(R(row11+1,j)-R(row11,j))/I1(row11,col11)
E2(1,j)=(R(row12+1,j)-R(row12,j))/I2(row12,col12)
end
You can get around your issue by the use of the eval function. My apologies, but I am reluctant to provide you with an actual 'answer' as I personally don't want to spread workaround solutions to problems that shouldn't exist in the first place. It just encourages the propagation of bad programming practice.
Hello
I tried it with evalin and assignin when E1 ... E50 are in the base Workspace. For example so (with Dimension 3)
A = zeros(3);
for i=1:50
var = strcat('E', num2str(i));
tt = evalin('base', var); % Matrix Ei is included and saved
Asoll = evalin('base', 'A'); % Actual Matrix
Aist = Asoll+tt; % New matrix
assignin('base', 'A', Aist); % Overwrite the variable in WS
end

Sign in to comment.

Answers (1)

i think you could use eval to create your variable names
for i=1:50
name=strcat('E',num2str(i));
prettyE(i)=eval(name);
end
sum(prettyE)

Asked:

on 5 Apr 2018

Community Treasure Hunt

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

Start Hunting!