# for loop values of certain output range

26 views (last 30 days)
sri kanth on 5 Sep 2019
Answered: Andrei Bobrov on 5 Sep 2019
x=3;
for c= -2:1:2;
for q= -2:1:2;
g= (c*x)+q*(c+x);
h= g(all((g>= 5) & (g<=10)));
disp([ 'at c=', num2str(c), 'at q=', num2str(q), ',g=', num2str(h)])
end
end
this code giving me all the itertions of c, q and the values of h are empty for out of range values and showing the values within the range
but i just want the values of h within the range and their respective c&q only
I really need help on this one, time is a factor.

Johannes Fischer on 5 Sep 2019
Two possible solutions:
x = 3;
idx = 1;
for c = -2:1:2;
for q = -2:1:2;
g = (c*x)+q*(c+x);
% g at this point is a scalar value, since in each iteration q and c are scalars.
% If you only want the output where g is in range:
if g >= 5 & g <= 10
disp([ 'at c=', num2str(c), 'at q=', num2str(q), ',g=', num2str(g)])
% You might also want to save these values
C(idx) = c;
Q(idx) = q;
G(idx) = g;
idx = idx+1;
end
end
end
There is also a possibly faster solution by not using for-loops
x = 3;
% the base array, as you use it for q and c
a = -2:2;
% now create two vectors whose combination is always unique, have a look at the arrays to confirm this.
c = repelem(a, numel(a));
q = repmat(a, [1, numel(a)]);
% compute all possible values for g
g = c*x + q.*(c+x);
% logical indices for all the elements of g that are in range
inRange = g>= 5 & g<=10;
G = g(inRange);
C = c(inRange);
Q = q(inRange);

Andrei Bobrov on 5 Sep 2019
x = 3;
c = -2:1:2;
q = -2:1:2;
g = c*x + q.*(c+x);
lo = g >= 5 & g <= 10;
out = table(c(lo),q(lo),g(lo),'Variablenames',{'c','q','g'});