How to run multiple for loops for values of x up to y and then from y up to z.
Ältere Kommentare anzeigen
Hello!
I am trying to write a script that will plot a graph of x against y.
My values of x go from 0 to b in 1000 steps.
I also have another value 'i' which is used in the initial for loop.
a and c are just two values inputted earlier in the script.
So to start with I have:
x = linspace(0,b,1000);
for i = imin : iinc : imax
for x < a
y = some function
end
for a < x < c
y = some function
end
end
I know that the two internal for loops wont run but im not sure how to write it so that they do.
Any help would be appreciated, Thanks!
2 Kommentare
Mark Smith
am 1 Dez. 2015
Guillaume
am 1 Dez. 2015
for p = x : a
when x is an array is the same as
for p = x(1) : a
Not at all what the OP is asking.
Antworten (2)
Guillaume
am 1 Dez. 2015
a = 3; b = 30; c = 4; %for example
x = linspace(0,b,1000);
%ignoring the i loop, since it's irrelevant to your question
for xx = x(x < a)
%do something with xx
fprintf('in 1st loop, xx = %f\n', xx);
end
fprintf('\n');
for xx = x(x > a & x < c)
%do something with xx
fprintf('in 2nd loop, xx = %f\n', xx);
end
You don't need loops. Use logical indices instead:
b = 10; x = linspace(0,b,1000);
ind = x < a;
y(ind) = x(ind).^2; % some function on x
c = 8;
ind = (a <= x) & (x < c);
y(ind) = x(ind).^3; % another function on x
plot(x,y)
1 Kommentar
Guillaume
am 1 Dez. 2015
"You don't need loops". Well, that depends on the unspecified function. It may only work on scalars.
Kategorien
Mehr zu MATLAB finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!