KatyB
KatyB

Reputation: 3990

trendline option (excel) in matlab

In excel I remember being able to select a specific trendline termed 'power' which according to the documentation:

'a power trendline is a curved line that is best used with data sets that compare measurements that increase at a specific rate — for example, the acceleration of a race car at one-second intervals. You cannot create a power trendline if your data contains zero or negative values'.

How can I implement this in matlab?

For example:

a = [15.5156,0.1995;
7.6003,0.2999;
9.4829,0.2592;
12.2185,0.2239;
23.4094,0.1811];

figure;scatter(a(:,1),a(:,2))

Upvotes: 2

Views: 5355

Answers (2)

Buck Thorn
Buck Thorn

Reputation: 5073

I plotted your data on excel and added a "power" trendline with the following equation:

y = 0.7188 x^{-0.4513}

which is of course a power law.

The analogue in Matlab is to perform a linear fit on the log-log transform of your data (which explains the constraints imposed by the "power" trendline app in excel):

x = a(:, 1);
y = a(:, 2);

p = polyfit(log(x), log(y), 1);   % <--  linear fit

which gives

p =

-0.4513   -0.3302

To overlay the trendline do like @kol but with the power law:

xx = linspace(min(x), max(x), 100);
yy = exp(p(2))*xx.^p(1);

figure;
hold on;
scatter(x, y);
plot(xx, yy, 'r-');

For xx or yy with some values<0 a data shift would be required before you attempt this.

Upvotes: 3

kol
kol

Reputation: 28698

Here is a working solution:

a = [15.5156,0.1995;
7.6003,0.2999;
9.4829,0.2592;
12.2185,0.2239;
23.4094,0.1811];

x = a(:, 1);
y = a(:, 2);
n = 2; % order of the fitted polynomial trendline
p = polyfit(x, y, n);
m = 1000; % number of trendline points (the larger the smoother)
xx = linspace(min(x), max(x), m);
yy = polyval(p, xx);

figure;
hold on;
scatter(a(:,1), a(:,2));
plot(xx, yy, 'r-');

You can easily put the trendline calculator code into a separate function.

Upvotes: 5

Related Questions