doing polyvar giving two conditions
2 views (last 30 days)
Show older comments
seema niran
on 16 Jan 2016
Commented: Star Strider
on 16 Jan 2016
i have a matrix xx(100*1) of elements less than and greater than 70 and a y matrix.p1=polyfit(xx,y,1)when xx<70 and p2=polyfit(xx,y,1);when xx>70 . i need to polyvar(p1,xx)for xx<70 and polyvar(p2,xx)for xx>70 and get the two condition as a single matrix. i tried with if loop but getting answer only for the else condition.is it possible to get answer in both conditions?
0 Comments
Accepted Answer
Star Strider
on 16 Jan 2016
See if this does what you want:
xx = linspace(1, 140); % Create Data
y = randi(99, 1, 100); % Create Data
p1 = polyfit(xx(xx<70), y(xx<70), 1);
p2 = polyfit(xx(xx>=70), y(xx>=70), 1);
y1 = polyval(p1,xx(xx<70));
y2 = polyval(p2,xx(xx>=70));
figure(1)
plot(xx(xx<70), y1, xx(xx<70),y(xx<70))
hold on
plot(xx(xx>=70), y2, xx(xx>=70),y(xx>=70))
hold off
grid
2 Comments
Star Strider
on 16 Jan 2016
Call the matrix (actually vector) containing ‘y1’ and ‘y2’, ‘yfit’ (or something more original), and since both are row vectors, define it as:
yfit = [y1 NaN y2];
If you want to define ‘xxfit’ in the same way (albeit redundantly in my example):
xxfit = [xx(xx<70) NaN xx(xx>=70)];
You could then plot them as:
figure(2)
plot(xx, y, 'bp') % Plot Original Data
hold on
plot(xxfit, yfit, '-r') % Plot Fitted Regression Lines
hold off
grid
The NaN values are to break up the regression lines and to make both vectors have equal lenghs.
Providing that your independent variables are well-behaved (such as ‘xx’ is here) you can do your regressions as I have done them here. If they are discontinuous or have extremely high magnitudes, you would have to centre and scale them to get the best and most robust fit. That involves adding the ‘S’ and ‘mu’ outputs to your polyfit calls and using them as well in your polyval calls. This is inconvenient, but will result in reliable parameter estimates and a reliable fit to the data. See the documentation for the functions for a full explanation.
And if you really want to ‘gild the lily’ and report the confidence intervals for the parameters ‘p1’ and ‘p2’, use the absolutely brilliant File Exchange contribution polyparci. Try it! you’ll like it!
More Answers (0)
See Also
Categories
Find more on Data Preprocessing 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!