Looping through mulyiple variable with names+numbers

조회 수: 1 (최근 30일)
Ansaar Dada
Ansaar Dada 2021년 3월 17일
답변: Mohammad Sami 2021년 3월 17일
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
Mohammad Sami
Mohammad Sami 2021년 3월 17일
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
Rik 2021년 3월 17일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Mohammad Sami
Mohammad Sami 2021년 3월 17일
You should use cell arrays to store your data. For example.
Arms = cell(25,1);
for i=1:2:25
Airms = Arms{i};
end

카테고리

Help CenterFile Exchange에서 MATLAB Code Analysis에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by