MATLAB: Concatenating an output matrix within inner and outer loops

concatenateloopsMATLAB

I am inputing data values in an outer loop which are used in calculations in an inner loop. The inner loop runs until a limit is reached whereby I would like to stop the inner loop and save the output data values that have resulted up until the limit has been reached in a matrix.
Then run the next set of values from the outer loop and recalculate another set of values in the inner loop until the limit is reached and append this data to the previous output matrix.
I have tried 'while' and 'for' loops with 'break' and 'continue' statements but so far I have only managed to get a 'k x z' matrix and when the limit is reached it is ignored and the inner loop runs through until the end of t. The step length in t is adjusted to set the resolution of the output in terms of being close to the limit within a certain accuracy.
Is there an easier way of approaching this problem !
k = 1;
for z = 1:10;
in1 = input1(k);
in2 = input2(k);
v=1;
for t = 0:0.1:5; % length of vector t can be varied so allow limit to be
% met in each inner loop
% calculations using in1 and in2 from outer loop
var1(v,k) = a;
var2(v,k) = b;
out = [a b];
limit = norm(out - in1);
% if limit < a constant value then stop inner loop and
% append out to create an Nx2 matrix after the limit is reached
% during every inner loop
v=v+1;
end
z=z+1
end

Best Answer

Hi,
In case you only want to break the inner for loop, you can try it this way
output=[];
k = 1;
for z = 1:10;
in1 = input1(k);
in2 = input2(k);
v=1;
for t = 0:0.1:5; % length of vector t can be varied so allow limit to be

% met in each inner loop

% calculations using in1 and in2 from outer loop

var1(v,k) = a;
var2(v,k) = b;
out = [a b];
limit = norm(out - in1);
if limit < a
break;
end
output = [output; out]; % appending data to output matrix

v=v+1;
end
z=z+1
end
In case you want to break both the inner and outer for loops, you can try it this way
output=[];
k = 1;
flag=0;
for z = 1:10;
in1 = input1(k);
in2 = input2(k);
v=1;
for t = 0:0.1:5; % length of vector t can be varied so allow limit to be
% met in each inner loop
% calculations using in1 and in2 from outer loop
var1(v,k) = a;
var2(v,k) = b;
out = [a b];
limit = norm(out - in1);
if limit < a
flag=1;
break; % to break inner loop
end
output = [output; out]; % appending data to output matrix
v=v+1;
end
if flag
break; to break outer loop
end
z=z+1
end
You need not increment z after inner for loop since it gets incremented by 1 in the outer for loop every time it runs. In case you want z to increment by n (number other than 1), you can write it as ‘for z=1:n:10’