for loop values of certain output range

5 Ansichten (letzte 30 Tage)
sri kanth
sri kanth am 5 Sep. 2019
Beantwortet: Andrei Bobrov am 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.

Akzeptierte Antwort

Johannes Fischer
Johannes Fischer am 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);

Weitere Antworten (1)

Andrei Bobrov
Andrei Bobrov am 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'});

Kategorien

Mehr zu Programmatic Model Editing finden Sie in Help Center und File Exchange

Produkte


Version

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by