Clear Filters
Clear Filters

Inserting Elements in middle of 1-D, 2-D, N-D Array

6 views (last 30 days)
Dear All,
I have got an array X = [1 2 3 4 5].
Want to refine the points by averaging neighbours and insert in the middle.
X1 = [1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0].. So, 5 points have become 9 points.
Is there an easier way to do it for a general array?
I would like to make it work in N-dimension also ... for refining the points.
Any help is much appreciated.
Thank You in advance,
K Vijay Anand.

Accepted Answer

Ameer Hamza
Ameer Hamza on 1 Dec 2020
Edited: Ameer Hamza on 1 Dec 2020
interp1() is suitable for such cases.
X = [1 2 3 4 5];
n_new = 9;
X_new = interp1(linspace(0,1,numel(X)), X, linspace(0,1,n_new))
For a high-dimensional case, you need to specify whether you want to apply it on a single dimension or all the dimensions?
  2 Comments
Vijay Anand
Vijay Anand on 1 Dec 2020
Edited: Vijay Anand on 1 Dec 2020
Thank You Mr.Ameer Hamza.
Amazing Logic !!!
Can you make it work for higher Dimensions also.
X = [
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
]
becomes,
X1 = [
1.0 1.5 2.0 2.5 3.0
2.5 3.0 3.5 4.0 4.5
4.0 4.5 5.0 5.5 6.0
5.5 6.0 6.5 7.0 7.5
7.0 7.5 8.0 8.5 9.0
]
Thanks in advance.
-Vijay
Ameer Hamza
Ameer Hamza on 1 Dec 2020
Edited: Ameer Hamza on 1 Dec 2020
Try interp2():
X = [
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
];
new_size = [5 5];
[xg, yg] = meshgrid(linspace(0,1,size(X,2)), linspace(0,1,size(X,1)));
[xg_, yg_] = meshgrid(linspace(0,1,new_size(2)), linspace(0,1,new_size(2)));
X_new = interp2(xg, yg, X, xg_, yg_);
or interpn() for a more general solution.

Sign in to comment.

More Answers (1)

Stephan
Stephan on 1 Dec 2020
Edited: Stephan on 1 Dec 2020
This may help
X = [
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0]
F = griddedInterpolant(X)
[xq,yq] = ndgrid(1:0.5:3);
Vq = F(xq,yq)
results in:
X =
1 2 3
4 5 6
7 8 9
F =
griddedInterpolant with properties:
GridVectors: {[1 2 3] [1 2 3]}
Values: [3×3 double]
Method: 'linear'
ExtrapolationMethod: 'linear'
Vq =
1.0000 1.5000 2.0000 2.5000 3.0000
2.5000 3.0000 3.5000 4.0000 4.5000
4.0000 4.5000 5.0000 5.5000 6.0000
5.5000 6.0000 6.5000 7.0000 7.5000
7.0000 7.5000 8.0000 8.5000 9.0000
  1 Comment
Vijay Anand
Vijay Anand on 1 Dec 2020
Thank a lot Mr.Stephan,
Works perfectly fine and solves my requirement !!!
Cheers,
Vijay

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!