How do I plot multiple lines of the same figure as if they are one?

3 次查看(过去 30 天)
I am trying to create a figure with four components on a set range and I cannot figure out how to divvy up the x axis among the equations without error. This is what I have so far:
x = 0:200000;
%Calculate first tax bracket
if x < 12000
y_1 = 0.1 .* x;
end
%Calculate second tax bracket
if (x > 12000)&&(x < 46000)
y_2 = 1200 + 0.15 .* x;
end
%Calculate third tax bracket
if (x > 46000)&&(x < 120000)
y_3 = 6300 + .25 .* x;
end
%Calculate fourth tax bracket
if x > 120000
y_4 = 24800 + .33 .* x;
end
%Plot
plotyy(x, y_1, x, y_2, x, y_3, x, y_4);
xlabel('Income (Dollars)');
ylabel('Taxed amount (Dollars)');
title('Income v. Taxed amount');

采纳的回答

David Sanchez
David Sanchez 2014-11-4
You can get your results also like this:
x = 0:200000;
%Calculate first tax bracket
y_1 = 0.1 .* x(x < 12000);
%Calculate second tax bracket
y_2 = 1200 + 0.15 .*x((x > 12000)&(x < 46000));
%Calculate third tax bracket
y_3 = 6300 + .25 * x((x > 46000)&(x < 120000));
%Calculate fourth tax bracket
y_4 = 24800 + .33.*x(x > 120000);

更多回答(1 个)

Star Strider
Star Strider 2014-11-4
Here’s a relatively simple way to do it:
x = 0:200000;
ytax = @(x) [(x<12000).*(0.1 .* x) + ((x >= 12000)&(x < 46000)).*(1200 + 0.15 .* x) + ((x >= 46000)&(x < 120000)).*(6300 + .25 .* x) + (x >= 120000).*(24800 + .33 .* x)];
figure(1)
plot(x, ytax(x))
xlabel('Income (Dollars)');
ylabel('Taxed amount (Dollars)');
title('Income v. Taxed amount');
My ‘ytax’ function creates an implicit if block, taking advantage of the fact that when a particular logical condition is 'true', it equates numerically to 1, and when 'false' to 0. Adding them together in the matrix in the function will produce a continuous variable that has the appropriate values over the appropriate regions of ‘x’.
I copied and pasted the ‘if’ conditions and equations directly from your code into ‘ytax’.

类别

Help CenterFile Exchange 中查找有关 Dialog Boxes 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by