conditional colouring graph problem
Show older comments
Hey, I have a problem with changing the colours on my graph conditionally; my function is as follows
function [t,vx,vy] = Q3_1400000(rocket,brake)
[t,ax,ay] = getAcceleration(rocket,brake);
vx = 0; vy = 0;
for n = 1:999;
vx(n+1) = vx(n) + ax(n+1);
vy(n+1) = vy(n) + ay(n+1);
k = 1:length(vx);
if vy(k) > vx(k)
c = 'r';
else
c = 'b';
end
end
plot(t,vx(k),c);
hold on
grid on
plot(t,vy(k),c);
xlabel('Time (s)');
ylabel('Velocity (m/s)');
title('\Velocity data for the rocket sled');
legend({'v_x','v_y'})
end
For some reason when the graph plots, the colour will always be the ' else ' colour and won't change at all. Does anybody know the solution to this please ?
Thanks
Accepted Answer
More Answers (2)
Chad Greene
on 27 Jan 2015
First create a logical array the size of vx and vy. It will have a 1 everywhere vy is bigger than vx, and a zero everywhere else:
vybigger = vy>vx;
Plot vx and vy, both in red where vy is bigger than vx:
plot(t(vybigger),vy(vybigger),'r');
hold on
plot(t(vybigger),vx(vybigger),'r');
Plot the rest of the data in blue:
plot(t(~vybigger),vy(~vybigger),'b');
plot(t(~vybigger),vx(~vybigger),'b');
1 Comment
Thomas Plank
on 28 Jan 2015
Edited: Thomas Plank
on 28 Jan 2015
Kelly Kearney
on 28 Jan 2015
An alternative method to Chad's (which works nicely if there's only one color switch, but may need some modification if there are multiple switches and you want solid lines) is to use patches with interpolated edge color:
t = linspace(0,2*pi,100);
vx = cos(t);
vy = sin(t);
vybigger = vy > vx;
hold on;
h(1) = patch([t NaN], [vx NaN], [vybigger NaN]);
h(2) = patch([t NaN], [vy NaN], [vybigger NaN]);
set(h, 'edgecolor', 'interp');
colormap([0 0 1; 1 0 0]);
Categories
Find more on Discrete Data Plots 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!