I have 3 x n
(n
is random number) matrix in MATLAB. Example for n=13
:
M = [40, 0, 0, 0, 41, 0, 0, 0, 0, 0, 41.6, 0, 20;
20, 0, 0, 0, 23, 0, 0, 0, 0, 0, 23, 0, 189;
102, 0, 0, 0, 192, 0, 0, 0, 0, 0, 96, 0, 21];
The number of zeroes between two non-zero numbers in each row is random, but this number is always the same between rows. I want to interpolate each row like this:
Minter = [40, 40.25, 40.5, 40.75, 41, 41.1, 41.2, 41.3, 41.4, 41.5, 41.6, 30.8, 20;
20, 20.75, 21.5, 22.25, 23, 23, 23, 23, 23, 23, 23, 106, 189;
102, 124.5, 147, 169.5, 192, 176, 160, 144, 128, 112, 96, 58.5, 21];
So I want to replace the zeroes with numbers obtained with linear interpolation method.
I wrote my own function to do this. I'm using the MATLAB function find
for searching for the indexes of numbers which are >0
, and then depending on difference between two indexes (from the find
function) and depending on the first right and left non-zero number (from the original matrix), I calculate numbers between these two non-zero numbers and replace zeroes with these numbers in the original matrix. I am working on each row separately.
This method work OK, but it is not very fast. Is any faster way in MATLAB? I tried the interp1
function, but without much success.