plotting line graph in different colors using while loop

I have a variable called "data" that's a set of data that's 49 rows x 40 columns. time is the first column (data(:,1)) and I want to plot time against the second column of the data (data(:,2)). When the the values in the second column are in certain ranges, I want the line of the line graph to be different colors. I wrote a while/ if else statement to do this, but it's not plotting anything and I'm not sure why. My code is written below. Thank you in advance!
figure
p = 1 %row that's changing (40 rows in all)
w = 2 %sensor/column number
hold on
while p <=size(data,1) %size of column
if data(p,w)<2.65
plot(data(p,1),data(p,2),'g')
elseif data(p,w)>=2.65 & data(p,w)<3.975
plot(data(p,1),data(p,2),'y')
else data(p,w)>=3.975
plot(data(p,1),data(p,2),'r')
end
p = p+1
end

 Akzeptierte Antwort

Star Strider
Star Strider am 11 Apr. 2021
This is relatively straightforward to do with scatter, however plot will not work with it.
colrfcn = @(x) (x(:)<2.65).*[0 1 0] + ((x(:)>=2.65) & (x(:)<3.975)).*[1 1 0] + (x(:)>=3.975).*[1 0 0];
x = 0:0.1:24; % Create Data For Plot
y = 4*(sin(2*pi*x/6)+1); % Create Data For Plot
figure
scatter(x, y, 15, colrfcn(y), 'filled')
grid
Experiment to get the results you want.
In theory at least the patch function could plot a multicoloured line, however definig a colormap that corresponds to what you want to do and that will work with patch seems not possible.

2 Kommentare

I didn't think about using a scatter plot - thank you this solved my problem!
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by