Best method to define a linear piece-wise function given limits and line equations?

I am writing a function(also new to matlab) that is fed the following:
1. the x limits of each piece
2. the slope and intercept values of each piece
3. the y values for which I am trying to find corresponding x values
How can I write a function that can take any number of pieces, and create a piece-wise function? I then would like to be able to feed it y values and return the corresponding x values. I currently can only write the function for a given number of pieces, not any number..?
My code thus far:
%%define the piecewise function
function x = peicewisehot(y,Hbreaks,slope)
%y; input from user
%Hbreaks; vertical breaks
%slope; slope of equation
%x = (y-b)/m
for i = 1:length(y)
if y(i) >= Hbreaks(1) & y(i) < Hbreaks(2)
x(i) = (y(i) - b(1))./slope(1);
elseif y(i) >= Hbreaks(2) & y(i) < Hbreaks(3)
x(i) = (y(i) - b(2))./slope(2);
else
x(i) = nan;
end
end

 采纳的回答

3 个评论

Thank you very much. I tried doing this and using interp1 seems to work great, however I am having issues using ppval to evaluate points. I am getting an error that says: "The input array does not seem to describe a pp function." The following is my code:
load HXData
B= unique(sort(TH(:)));
numsecB = size(B) - 1;
slopeB = zeros(1,numsecB);
s = [length(TC) length(TH)];
for i=1:numsecB
tester = (B(i)+B(i+1))/2;
for j=1:s(2)
if (tester >= TH(j,2) & tester <= TH(j,1))
checkB(i,j) = 1;
slopeB(i) = slopeB(i)+ KH(j);
else
checkB(i,j) = 0;
end
end
end
%Calculates the total enthalpy needed for each stream
Hhot=entHC1(B,slopeB); %enthalpy needed for each hot stream section
Hhotpt(1)=0; %calculates the y value of the hot stream at each point
for i=2:(length(Hhot)+1)
Hhotpt(i) = (Hhot(i-1)+Hhotpt(i-1));
end
u = linspace(B(1), B(end), 1000)';
[k,k] = histc(u,B);
n = length(B);
k(k == n) = n-1;
yinterp1 = interp1(B,Hhotpt,u, 'linear')';
I also was wondering if this is how i would correctly evaluate a point on the piecewise curve:
check = ppval(yinterp1, 40);
yinterp1 = interp1(B, Hhotpt, 'linear', 'pp');
Notice the "u" is not passed, as you are not interpolating at specific points when you create the pp.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Interpolation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by