Looping through mulyiple variable with names+numbers
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi everyone,
Been trying to use a for loop for my 25+ variables, but to no avail. Please have a look at this snippet of a code:
%%%%%%%%%%%%%%%%%%%% working code
nb_iterations = 5;
A1rms = 230; P1rad = 0;
A3rms = 0*A1rms; P3rad = 0;
A5rms = [0:0.00775:0.031]*A1rms; P5rad = 0;
A7rms = [0:0.00695:0.0278]*A1rms; P7rad = pi;
A9rms = 0*A1rms; P9rad = 0;
V_As = []; V_Ps = [];
for tr = 1:nb_iterations
A3rms_int = rand(1)*max(A3rms);
A5rms_int = rand(1)*max(A5rms);
A7rms_int = rand(1)*max(A7rms);
A9rms_int = rand(1)*max(A9rms);
V_As = [V_As; [A3rms_int, A5rms_int, A7rms_int, A9rms_int]];
P3rad_int = rand(1)*P3rad;
P5rad_int = rand(1)*P5rad;
P7rad_int = rand(1)*P7rad;
P9rad_int = rand(1)*P9rad;
V_Ps = [V_Ps; [P3rad_int, P5rad_int, P7rad_int, P9rad_int]];
end
%%%%%%%%%%%%%%%%%%%% efficient code (not working)
selected_harm = 3:2:9;
for tr = 1:nb_iterations
for idx = length(selected_harm)
A(idx)rms_int = rand(1)*max(A(idx)rms);
V_As = [V_As; [A3rms_int, A5rms_int, A7rms_int, A9rms_int]];
P(idx)rad_int = rand(1)*P(idx)rad;
V_Ps = [V_Ps; [P3rad_int, P5rad_int, P7rad_int, P9rad_int]];
end
end
The first code works, but I would like to have a loop that performs A3rms_int all the way to A9rms_int in order to increase readability and be more efficient as I have variables all the way up to A25rms_int. And similarly, for the P variables.
Thank you in advance for your help!
2 comentarios
Mohammad Sami
el 17 de Mzo. de 2021
You should use cell arrays to store your data. For example.
Arms = cell(25,1);
for i=1:2:25
Airms = Arms{i};
end
Rik
el 17 de Mzo. de 2021
Mohammad, please move your comment to the answer section.
This issue is due to poor design. You should not store information in a variable name, that is what you have variables for.
Respuestas (1)
Mohammad Sami
el 17 de Mzo. de 2021
You should use cell arrays to store your data. For example.
Arms = cell(25,1);
for i=1:2:25
Airms = Arms{i};
end
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!