how plot two slopes for one curve

3 ビュー (過去 30 日間)
Hisham
Hisham 2014 年 3 月 29 日
回答済み: Naga 2024 年 9 月 18 日
Hi,
I have one curve. I want to plot two slopes; the first slop is for points 1,2,3 and 4. The second slope is to plot the rest of the points. I attached a figure of this.

回答 (1 件)

Naga
Naga 2024 年 9 月 18 日
Hello Hisham,
It understand you want to plot two different slopes for different segments of your data. Based on the image you provided, here’s how you can achieve that:
  1. Separate the points for the two slopes.
  2. Use the polyfit function to find the slope for each segment.
  3. Use the plot function to visualize the data points and the fitted lines.
Here’s a sample code:
% Define data points
x = 2000:500:7000;
y = -17:0.5:-12;
% Separate points for two slopes
x1 = x(1:4); y1 = y(1:4);
x2 = x(5:end); y2 = y(5:end);
% Calculate slopes
p1 = polyfit(x1, y1, 1);
p2 = polyfit(x2, y2, 1);
% Plot data points and fitted lines
figure;
scatter(x, y, 'filled'); hold on;
plot(x1, polyval(p1, x1), '-r', 'LineWidth', 2);
plot(x2, polyval(p2, x2), '-b', 'LineWidth', 2);
% Add labels and legend
xlabel('X-axis'); ylabel('Y-axis');
legend('Data points', 'First slope', 'Second slope');
title('Plot with Two Slopes');
hold off;
Refer the below documentation links to read more about the functions:
  1. polyfit: https://www.mathworks.com/help/matlab/ref/polyfit.html
  2. polyval: https://www.mathworks.com/help/matlab/ref/polyval.html

カテゴリ

Help Center および File ExchangeScatter Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by