How can I calculate the slope of a line given two points?

153 views (last 30 days)
I need a function which can output the slope of a 2D line given two points. Ofcourse, I could just use m = (y2-y1)/(x2-x1), however, I have a long list of points/lines which I need to find the slope of and I don't believe this would be the most efficient method.
Something similar to the pdist2(point_a, point_b) function which I've previously used to find the distance between two points would be ideal.
Thanks in advance.

Accepted Answer

Image Analyst
Image Analyst on 21 Feb 2015
Edited: Image Analyst on 22 Feb 2015
If you have the endpoints in 4 arrays, use a vectorized divide:
slopes = (y2 - y1) ./ (x2 - x1);
It is efficient.
  9 Comments
sisir regmi
sisir regmi on 21 Apr 2019
its days matrix dimension must agree
X Y
%===================
0.0600 13.22
0.1550 179.6
0.1800 438.2
0.2500 687.8
0.2800 981.3
0.4180 1152
0.5540 931
1.7370 91.24
1.8220 80.37
1.8230 37.61
1.8240 12.09
1.8250 70.55
2.0290 96.34
2.0620 125.6
2.0730 73.59
2.0750 57.15
2.0910 88.75
2.1080 80.1
2.1100 111.6
2.1570 258.1
3.1200 40.66
3.2600 42.7
3.3700 60.61
3.4400 236.8
3.5400 239.6
3.5600 212.1
3.5800 128.4
3.9200 46.09
4.0800 40.58
4.1700 47.02
4.1900 90.86
4.3600 174.5
4.3800 244.2
4.3900 316.9
4.4500 482
4.4560 614.4
4.4400 775.3
4.4600 923.3
4.3500 782.3
4.5500 486.9
4.6900 75.65
5.1380 35.83
5.2800 31.34
5.4000 35.01
5.5400 28.84
5.6700 36.18
5.7800 31.63
5.8000 16.6
5.8100 11.26
5.9000 4.97
5.9001 11.38
5.9100 10.54
5.9200 9.34
6.1900 13.16
6.2000 21.86
6.2100 28.86
6.4230 738.6
6.5700 148.5
6.6500 469.1
6.7100 763.6
6.7200 914.6
6.8300 301.9
6.8500 192
6.9200 118.5
7.1100 79.65
7.2500 49.06
];
figure(1)
slope=diff(y)./diff(x);
matrix dimensions must agree.
Error in untitled5 (line 72)
slope=diff(y)./diff(x)
Image Analyst
Image Analyst on 21 Apr 2019
Well, why do your x and y have different sizes? That doesn't make sense, so explain it to me.

Sign in to comment.

More Answers (1)

Neal Young
Neal Young on 22 Feb 2015
Hi, thank you both for the quick reply. I've noted the points below. Each point is connected to the subsequent point via a bar and I've to find the slope of each of these bars. Therefore the slopes = (y2 - y1) ./ (x2 - x1) formula should be most efficient.
A = [135, 86.5]; B = [152.7, 119]; C = [142.9, 114.2]; D = [192.4, 164.7]; E = [151.8, 170.4]; F = [135.4, 190.6]; G = [143.1, 184]; H = [121.4, 208];

Community Treasure Hunt

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

Start Hunting!