MATLAB: Changing varible/struct name on both side with a loop inside a function

change namedefine namedynamic variable namesevalfor loopstructvariablevariable in a loopvariable in loop

Hello everyone,
I got a problem when I want to read some data from many structs. I got like 8 Struct, which is from E1…..E8.
Each of these structs got 9 variables/fields stored inside.
I need to do the same algoritmen for each of them, and then sum them up in the end.
Each of these struct got a real part and imaginary part for x,y,z direction.
I want to use this function for each of my struct and also change my variable name at the same time
for i=1:8
e(i)RealX= interp3(xx,yy,zz,E1.Real_Part_of_X_Comp_0s,xx0,yy0,zz0);
e(i)RealY= interp3(xx,yy,zz,E1.Real_Part_of_Y_Comp_0s,xx0,yy0,zz0);
e(i)RealZ= interp3(xx,yy,zz,E1.Real_Part_of_Z_Comp_0s,xx0,yy0,zz0);
e(i)ImgX = interp3(xx,yy,zz,E(i).Imaginary_Part_of_X_Comp_0s,xx0,yy0,zz0);
e(i)ImgY = interp3(xx,yy,zz,E(i).Imaginary_Part_of_Y_Comp_0s,xx0,yy0,zz0);
e(i)ImgZ = interp3(xx,yy,zz,E(i).Imaginary_Part_of_Z_Comp_0s,xx0,yy0,zz0);
end
EX= e1RealX.*e1ImgX+......e8RealX.*e8ImgX;
EY= e1RealY.*e1ImgY+......e8RealY.*e8ImgY;
EZ= e1RealZ.*e1ImgZ+......e8RealZ.*e8ImgZ;
E = EX+EY+EZ
I did look at this FAQ, which many people refer to, but I just don't think it fits my problem http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C….2CA10_in_a_loop.3F
I am not very strong at matlab and I would like to hear some advice to solve this in a smart way….
Thank you for help!
Nick

Best Answer

allE = {E1, E2, E3, E4, E5, E6, E7, E8};
for i = 1 : length(allE)
e(i).RealX = interp3(xx, yy, zz, allE{i}.Real_Part_of_X_Comp_0s, xx0, yy0, zz0);
e(i).RealY = interp3(xx, yy, zz, allE{i}.Real_Part_of_Y_Comp_0s, xx0, yy0, zz0);
e(i).RealZ = interp3(xx, yy, zz, allE{i}.Real_Part_of_Z_Comp_0s, xx0, yy0, zz0);
e(i).ImgX = interp3(xx, yy, zz, allE{i}.Imaginary_Part_of_X_Comp_0s, xx0, yy0, zz0);
e(i).ImgY = interp3(xx, yy, zz, allE{i}.Imaginary_Part_of_Y_Comp_0s, xx0, yy0, zz0);
e(i).ImgZ = interp3(xx, yy, zz, allE{i}.Imaginary_Part_of_Z_Comp_0s, xx0, yy0, zz0);
end
Notice that this uses only the techniques from the FAQ link you indicated.