Assign index to a matrix?
Afficher commentaires plus anciens
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 commentaires
David Fletcher
le 5 Avr 2018
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.
Neje
le 5 Avr 2018
David Fletcher
le 5 Avr 2018
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.
Christian Dieterich
le 5 Avr 2018
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
Réponses (1)
Dennis
le 5 Avr 2018
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)
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!