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

3 views (last 30 days)
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
  1 Comment
Stephen23
Stephen23 on 21 Jan 2016
The best solution would be use a non-scalar structure, exactly as per Walter Roberson's Answer. This is the most efficient and neatest solution.
Note that creating variable names dynamically is inefficient, slow and buggy, do not be tempted to program using dynamic variable names. Read this to know why:

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 21 Jan 2016
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!