How can I loop each line of a script as the conditional in a new if statement?
1 次查看(过去 30 天)
显示 更早的评论
I have a large number of conditional statements (4280) that are in a script. From each conditional statement I need to analyze and manipulate it into a specific matrix and then have it put the results from each conditional state into one final matrix. The analysis and steps are the same for each conditional statement so a loop should do the trick, i just cant figure out how to put the initial script into each loop. I believe something like fgetl should work, but cant figure it out. Any help is appreciated. THANKS!
%Simplified Example
i=1;
j=1;
X=rand(10,3);
%Conditionals from the script
x(i,1)>0.5 & x(i,2)<0.5
x(i,1)>0.5 & x(i,2)>0.5
%...And so on with more complexity
for i=1:10
if (lines from the script)
x2(j,:)=x(i,:)
j=j+1;
xmean=grpstats(x2,3) %for the conditional in line 1
end
%then repeat this over all the lines into a matrix of all the values and conditionals.
%then have a final matrix of something like ('conditional number','true of each conditional','value')
2 个评论
dpb
2015-4-28
I can't follow from the description; need more specifics and fewer generalizations of just what the conditions and lines are referring to.
The two conditionals above are identical as far as my old eyes can tell and don't need any loops; simply use as a conditional logical address. If you mean you have written expressions like the above and want to compute those dynamically, that's a little different and generally is frowned upon as that's eval. There's normally "a better way" but w/o more specifics not sure we can come up with the right answer here.
How above a small subset but something that can be run to show input/output for a sample case that can test ideas out on? Surely if there are only a handful but representative that'll be as good as 5000 for algorithm design.
回答(1 个)
Joseph Cheng
2015-4-28
编辑:Joseph Cheng
2015-4-28
Well.... I too am not entirely sure what you're trying to accomplish but if the formatting of your conditional script is always in the format "x(i,1){operator}{number} & x(i,2){operator}{number}" then we can use sscanf to parse out the conditions for if statements or to a switch/case. the pattern can be adapted to cover more complex conditions but without an example i'll only use it in the example below:
ind=1;
string = ['x(i,1)>0.5 & x(i,2)<0.5';'x(i,1)>0.5 & x(i,2)>0.5']
A = sscanf(string(ind,:),['x(i,1)%1s%f & x(i,2)%1s%f'])
which would return
A =
62.0000
0.5000
60.0000
0.5000
where 62 and 60 are the decimal representation of < and >. regexp() would possibly be better to capture more complicated cases but haven't thought about it toomuch since there isn't an example
This would get you away from using the frowned upon eval
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!