MATLAB: Is there the more elegant way to do this

evalevalinlist of variablesmetapitfall

I have 10 matrices(10*24 size each) named A1,A2,,,,A10.Now i want this
E1=sum(A1);
E2=sum(A2);
till E10=sum(A10);
thus E1,E2,,,,,E10 each matrices size of 1*24 . so there is another way to write in short code ?

Best Answer

  • Hi Mukesh Kumar
    Elegance like beauty lives in the eyes of the observer, so while some people abhor the command evalin, I consider it's a really powerful and elegant option to simplify the generation of variables.
    1.
    Simulating data
    A1=randi([-10 10],3)
    A1 =
    -2 4 -10
    3 -10 -8
    -7 -5 7
    >> A2=randi([-10 10],3)
    A2 =
    4 -10 6
    -4 -1 6
    9 -2 -7
    >> A3=randi([-10 10],3)
    A3 =
    0 4 4
    -1 5 3
    3 -5 -7
    2. Code that writes code
    for k=1:1:3
    str1=['E' num2str(k) '=sum(A' num2str(k) ')'];
    evalin('base',str1)
    end
    E1 =
    -6 -11 -11
    E2 =
    9 -13 5
    E3 =
    2 4 0
    if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
    To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
    thanks in advance
    John BG