Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Replacing zeros in a matrix with an interpolation

Asked by Bob Choy

Bob Choy (view profile)

on 17 Nov 2012

I have a matrix, on which the values become larger as columns go, but some values in that matrix are zero.

E.g. [1,1,1;2,0,2;3,3,3]

I want to replace the values that are zero with an interpolation. In this example theres an increment of 1 per line, so the value zero should become the previous value in that column (1) plus the average increment value (1). Therefore becoming the value 2.

Returning the matrix [1,1,1;2,2,2;3,3,3]

So how can I do this given any matrix, with whatever values.

EDIT: Okay I probably got myself misunderstood, I dont want the zero values to be always the previous value + 1. Let me illustrate further:

M = [1,10;1,0;1,0;1,22]

-Values m(2,2) and m(3,2) are both zero.

-Values m(1,2) and m(4,2) are 10 and 22 which means in 3 rows there was an increment of 12 values, averaging and increment of 4 values per row.

-Interpolating, the values for m(2,2) and m(3,2) should be 14 and 18 respectively.

Thanks alot for you help, appreciated.

2 Comments

Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 17 Nov 2012

What if 0 is in the first line

Bob Choy

Bob Choy (view profile)

on 17 Nov 2012

This shouldnt be a problem, there are never zeros in the first line, meaning I only want to do this for the second line and forth.

Thank you.

Bob Choy

Bob Choy (view profile)

Products

No products are associated with this question.

1 Answer

Answer by Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 17 Nov 2012
Edited by Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 17 Nov 2012
Accepted answer

Ok, if the first line is different from zero

a= [1,1,1;2,0,2;0,3,3]
inc=1;
idx=find(~a)
a(idx)=a(idx-1)+inc

5 Comments

Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 18 Nov 2012

You said the average increment is, for example for the first column:

 (30-1)/4= 7.25,

why are you expecting inc to be 4?

Bob Choy

Bob Choy (view profile)

on 18 Nov 2012

Nevermind what I said before, I have a new problem though, Im doing this with a big with lots of zeros to be replaced, and everytime it replaces a zero it returns that matrix, resulting in the program returning thousands of matrixes until it finally gets to the final one with all zeros replaced, this process takes a huge amount of time. How can I tell matlab to return only the final matrix and not show me every one of them?

Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 18 Nov 2012

Bob, If you have a new problem, post a new question, and make it as clear as possible

Azzi Abdelmalek

Azzi Abdelmalek (view profile)

Contact us