Using 'for loop' to plot
Show older comments
I have three set of data (y1, y2 and y3). And I want to only plot a certain range within each data set.
I want to perform this task in two ways. I succedded in the first method to plot the graph without a 'for loop'.
But in the second method, I want to use a 'for loop'. However, I am a bit confused. Can you help me out. Thanks
clear all; close all;clc
x1=linspace(0, 11, 25);y1=2*x1.^2;
f1=max(find(x1<=2));f2=min(find(x1>=10));
x2=linspace(-2, 15, 17);y2=x2.^2;
f3=max(find(x2<=3));f4=min(find(x2>=14));
x3=linspace(-5, 25, 21);y3= (7.*x3)+ 5;
f5=max(find(x3<=5));f6=min(find(x3>=21));
%% Method 1
plot(x1(f1:f2),y1(f1:f2), 'r');hold on;plot(x2(f3:f4),y2(f3:f4), 'k');hold on;plot(x3(f5:f6),y3(f5:f6),'b')
xlabel('X');ylabel('Y')
return
%% Method 2
A=[y1 y2 y3];
B=[x1 x2 x3];
figure;
for i=1:length(A);
for j=1:length(B);
f1=max(find(x1<=2));f2=min(find(x1>=10));
f3=max(find(x2<=3));f4=min(find(x2>=14));
f5=max(find(x3<=5));f6=min(find(x3>=21));
plot(B(i),A(i))
hold on;
end
end
2 Comments
Walter Roberson
on 2 Dec 2022
Note that you can do things like
mask = x1 > 2 & x1 <10;
plot(x1(mask), y1(mask))
Grace
on 3 Dec 2022
Accepted Answer
More Answers (1)
Of course you can do it with a loop.
I am not clear as to why you are constructing an x range that is not just the inside of the range that you are masking off, but whatever...
xlow = [0, -2, -5];
xhigh = [11, 15, 25];
masklow = [2, 3, 5];
maskhigh = [10, 14, 21];
colors = {'r', 'k', 'b'};
polycoeffs = [2 0 0; 1 0 0; 0 7 5];
for K = 1 : length(xlow)
x = linspace(xlow(K), xhigh(K));
y = polyval(polycoeffs(K,:), x);
mask = masklow(K) < x & x < maskhigh(K);
plot(x(mask), y(mask), colors{K});
hold on
end
hold off
xlabel('X');
ylabel('Y')
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


