Trouble with MATLAB vectorized piecewise function

2 views (last 30 days)
I am having trouble writing a function in a vectorized way that can take a vector and output a vector with the same dimension.
My function maps t to f(t) like a regular 1D function in xy plane (t is like x). It also takes a set of data points in the form of two column vectors, such as a matrix A(:,2) as input. The first column is assumed to be x-values and second column to be y-values. The function extends the data points of A to all of real space where any data points outside of the domain of A should return a y-value of 0. In other words, I want the function to:
Output 0 when the input t isn't within the x-values included in the first column of A. Output the y-values in the second column of A when the input t is within the first column of A.
For any input t between x-values in the first column of A, I use a linear formula to connect adjacent points of A.
The MATLAB code is as follows:
function f = Af(t,A)
no_A= length(A);
spac_A= (A(end,1)-A(1,1))./length(A);
f = zeros(size(t));
k = floor((t-A(1,1)) ./ spac_A) + 1;
f(find(k < 1)) = 0;
f(find(k >= 1 & k < no_A-1)) = A(k,2) + (A(k+1,2)-A(k,2))./(A(k+1,1)-A(k,1)).*(t-A(k,1));
f(find(k == no_A)) = A(k);
f(find(k > no_A)) = 0;
end
The problem is whenever I have input t outside of the x-values included in the first column of A, the function still tries to access the corresponding A(k,2) which results in error because k is an index restricted to the length of A. I have trouble ruling out that situation while keeping the function in a vectorized form. Do you have any good solutions? I thank you in advance for your time reading my problem.

Answers (1)

Fangjun Jiang
Fangjun Jiang on 28 Jul 2011
There is a built-in function to do that. It is called interp1(). In your case:
A=[1:5; 1:5]'
t=-2:2:6
f=interp1(A(:,1),A(:,2),t,'linear',0)
A =
1 1
2 2
3 3
4 4
5 5
t =
-2 0 2 4 6
f =
0 0 2 4 0

Categories

Find more on Animation 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!