constrain the csapi fitting to positive values

I have a vector x of size 25 x 1 and a vector y of size 25 x 1. I subject them to spline fitting function (as below) and I get a function whose values go in the negative range. I know apriori that the values should be positive. Is there any method to constrain the fitting according to this using csapi?
cs = csapi(x,y); % vectors of size 25 x 1
figure(11)
fnplt(cs,2);
hold on
plot(x,y,'o')
hold off
xlabel('pixel values from the intensity patch')
ylabel('pixel values from the IR patch')

 Akzeptierte Antwort

John D'Errico
John D'Errico am 7 Jun. 2023
Bearbeitet: John D'Errico am 8 Jun. 2023
I'm sorry, biut you cannot constrain an interpolating spline built by csapi to be everywhere positive. The mathematics of how the spline is built will not allow constraints of that form.
You CAN use an interpolant like pchip however. By design, it does not go beyond the range of your data, so if your data never goes negative, then pchip also will never go negative.
A minor problem with pchip is you will probably not like the way it behaves near a peak, in that it also will not predict well near a peak. So a trick I have found that can work, is you just use a spline to interpolate the log(y), as a function of x. For example...
x = 0:25;
y = rand(size(x)).^3;
I've explicitly chosen a curve that will create a spline that goes negative on interpolation, if we use a basic spline (thus csapi).
spl0 = csapi(x,y);
fnplt(spl0,'b')
hold on
plot(x,y,'ro')
yline(0)
hold off
Now, we CAN just use pchip.
splp = pchip(x,y);
plot(x,y,'ro')
hold on
fnplt(splp,'b')
yline(0)
hold off
If you look at the first plot, using csapi, you can see it goes below zero sometimes. But the curve drawn by pchip tends to look "wrong" near the peaks.
So a trick that can work is this one:
splL = csapi(x,log(y));
plot(x,y,'ro')
hold on
fplot(@(x) exp(fnval(splL,x)),[min(x),max(x)],'b')
yline(0)
hold off
It produces peaks that look spectral, but never goes below zero. If you see what I did, I interpolated the LOG of y as a spline, but then exponentiated the result. The result may be what you are looking for. Just be careful, if y is ever exactly zero, you need to use another trick. And, if you think about it, it sort of makes sense, because logs and spectra tend to go well together.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by