for loop values of certain output range

1 次查看(过去 30 天)
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
Johannes Fischer 2019-9-5
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);

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2019-9-5
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'});

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by