How to create a loop function for a set of parameters from a file to define each parameters as variables

조회 수: 1 (최근 30일)
I want to simplify my code by creating a loop function (for or switch). The data is given from a file (parameters) and I input my variable for each cell of different rows from the parameter file.
Please help me on how to implement this. Thank you.
xmin = parameters(1);
xmax = parameters(2);
ymin = parameters(3);
ymax = parameters(4);
dx = parameters(5);
gamma = parameters(6);
threshold = parameters(7);
Npos = parameters(8); Npos_1 = parameters(9:10);
Npos_2 = parameters(11:12);
Npos_3 = parameters(13:14);
Npos_4 = parameters(15:16);

채택된 답변

Guillaume
Guillaume 2019년 1월 11일
In my opinion, the best thing would be change the way your read that file so that it's read directly into the variables (or better a table or structure) that you want instead of that paramaters array.
As it is, this may simplify your code slightly:
parameters = mat2cell(parameters, 1, [1 1 1 1 1 1 1 1 2 2 2 2]); %asumming that paramters is a 1x16 row vector
[xmin, xmax, ymin, ymax, dx, gamma, threshold, Npos, Npos_1, Npos_2, Npos_3, NPos_4] = parameters{:};
  댓글 수: 3
Guillaume
Guillaume 2019년 1월 11일
The only way you could use a loop would be with eval. This would make the code slower, harder to debug and certainly not simpler.
Stephen23
Stephen23 2019년 1월 12일
"I wanted to simplify it to a simpler version (such as putting it in a loop)"
Putting it into a loop would require magically creating variable names, which would make your code slower, buggier, harder to debug, and more obfuscated. Read the link in my answer to know why.

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

추가 답변 (2개)

Stephen23
Stephen23 2019년 1월 11일
편집: Stephen23 2019년 1월 11일
Dynamically creating variable names is not recommended. Read this to know why:
Instead you can easily use a table, or generate fieldnames of a structure:
>> P = randi(99,1,16) % fake 1x16 data.
P =
87 6 86 48 15 10 52 54 15 35 10 20 33 58 34 42
>> F = {'xmin','xmax','ymin','ymax','dx','gamma','threshold','Npos','Npos_1','Npos_2','Npos_3','Npos_4'};
>> S = cell2struct(mat2cell(P,1,[ones(1,8),1+ones(1,4)]),F,2)
This gives a structure S with the following fields:
xmin = 87
xmax = 6
ymin = 86
ymax = 48
dx = 15
gamma = 10
threshold = 52
Npos = 54
Npos_1 =
15 35
Npos_2 =
10 20
Npos_3 =
33 58
Npos_4 =
34 42

pirpyn
pirpyn 2019년 1월 11일
편집: pirpyn 2019년 1월 11일
Since you seems to have a constant array and not a cell one, look at the deal function.
[Y1, Y2, Y3] = deal(X)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by