How to temporarily stop a script, extract data, and then continue?
9 views (last 30 days)
Show older comments
How can I temporarily pause a for loop, extract data at that point, and then continue the script? Here is my code:
A = importdata('HW8.2.Custom1.txt','%f%f%f', ' ',1);
n=length(A);
for i = 1:2:n-1
line_desc = A{i};
line_data = str2num(A{i+1});
if strcmp(line_desc,'inlet');
P_in = line_data(1);
z_in = line_data(2);
D_in = line_data(3);
elseif strcmp(line_desc,'exit');
P_out = line_data(1);
z_out = line_data(2);
D_out = line_data(3);
elseif strcmp(line_desc,'fitting');
K_L = line_data(1);
V = line_data(2);
Element_Num = line_data(3);
elseif strcmp(line_desc,'pipe');
L = line_data(1);
D = line_data(2);
rough = line_data(3);
delta_z = line_data(4);
Element_Num = line_data(5);
elseif strcmp(line_desc,'pump');
H_s = line_data(1);
Element_Num = line_data(2);
else strcmp(line_desc,'turbine');
H_s = line_data(1);
Element_Num = line_data(2);
end
end
What I am trying to do is stop the for loop each i, make variables based on that i, and then continue the loop and repeat for each iteration. Right now, however, it is just running the whole for loop and then giving me variables based on the final iteration (when i = n-1) Is it possible to pause it after each iteration and what function would I use?
0 Comments
Accepted Answer
Jan
on 25 Apr 2017
Edited: Jan
on 25 Apr 2017
What about storing the values in vectors? Then there is no need to stop the loop:
n = length(A);
P_in = zeros(1, n); % Pre-allocate
z_in = zeros(1, n);
D_in = zeros(1, n);
inlet_i = 0;
for i = 1:2:n-1
line_desc = A{i};
line_data = str2num(A{i+1});
switch line_desc
case 'inlet'
inlet_i = inlet_i + 1;
P_in(inlet_i) = line_data(1);
z_in(inlet_i) = line_data(2);
D_in(inlet_i) = line_data(3);
case ... same for the other variables
end
P_in = P_in(1:inlet_i); % Crop unused elements
z_in = z_in(1:inlet_i);
D_in = D_in(1:inlet_i);
Stopping scripts to manipulate the data is "meta-programming" and in consequence prone to errors and hard to debug.
2 Comments
Jan
on 25 Apr 2017
@Neil: At first the vector P_in is allocated and filled with zeros. This is more efficient than letting it grow iteratively. The variable "inlet_i" is the cursor, which defines where to fill in the new values if the "inlet" keyword appears. A more general example:
x = zero(1, 10);
ix = 0;
for k = 1:10
if rand < 0.5
ix = ix + 1
x(ix) = k;
end
end
x = x(1:ix)
Let this run and observe what's going on in the debugger. This selects randomly 10 numbers from 1 to 10 and crops the undefined elements afterwards. Not really useful, but a demonstration :-)
More Answers (1)
Image Analyst
on 25 Apr 2017
Why not just set a breakpoint wherever you want it to stop? Then do your stuff in the command window, then tell it to "Continue".
Tutorial on debugging:
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!