How do I shade the area between two STAIR curve
6 views (last 30 days)
Show older comments
I am trying to fill the area between two stair curves. I can do this successfully between lines but I need stairs.
This is the code that I wrote:
X=[x,fliplr(x)];X=[X;X];
Y=[y2,fliplr(y1)]; Y=[Y;Y];
clf;
fill(X([2:end end]),Y(1:end),rgb('orange'),'FaceAlpha',0.2);
Where x represents the common, evenly spaced axis and y1 and y2 represent the data for the lower and upper curve respectively. My problem is that when graphed the lower curve is offset by one "bin". I understand this is coming from the X([2:end end]) but this is the inly way I found to fill with the stairs.
I would appreciate any suggestions.
Deborah
1 Comment
Florian
on 25 Jan 2016
Edited: Florian
on 25 Jan 2016
I did not find a solution either, so I figured out a way myself.
Here is a little example: - I "imitate" the stairs function (by keeping the previous y-value until the next) - I did not manage to fill the space between the stairs "in one step" (it always looked weird), so I did it piecewise. (for-loop)
Maybe my solution is not the best but it works.
% X-Data
X = 0:23;
% Y-Data
Y1 = sin(X .* (2*pi/max(X)) ); % Func 1
Y2 = Y1 + 0.1*sin(X .* (2*pi/max(X)) ); % Func 2
% Create "Stairs-Function"
Xi = [X(sort([1:length(X), 2:length(X)])), X(end)+(X(end)-X(end-1))];
Y1i = [Y1(sort([1:length(X), 1:length(X)]))];
Y2i = [Y2(sort([1:length(X), 1:length(X)]))];
% Plot Stairs
figure(2)
hold off;
plot(Xi, Y1i, 'r-');
hold all;
plot(Xi, Y2i, 'k-');
% Fill Stairs
for i = 1:2:length(Xi)
if ( Y1i(i) > Y2i(i) ) % Upper
xx = [Xi(i:i+1), fliplr(Xi(i:i+1))];
yy = [Y1i(i:i+1), fliplr(Y2i(i:i+1))];
fill(xx, yy, 'k', 'FaceAlpha',0.2);
elseif ( Y2i(i) > Y1i(i) ) % Lower
xx = [Xi(i:i+1), fliplr(Xi(i:i+1))];
yy = [Y1i(i:i+1), fliplr(Y2i(i:i+1))];
fill(xx, yy, 'r', 'FaceAlpha',0.2);
else % Identical
% do nothing
end
end
% Draw Lines Again
plot(Xi, Y1i, 'r-');
plot(Xi, Y2i, 'k-');
title('Coded Stairs Function');
Cheers Florian
Answers (0)
See Also
Categories
Find more on Interpolation 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!