Koen Ver
Koen Ver

Reputation: 137

Merge arrays with unequal number of columns

I have around 100 1D arrays I'd like to merge to a matrix. The arrays have 140 to 180 columns.

Is it possible to merge these 1 x (140-180) arrays to a matrix with a dimension of 100 (amount of arrays) x 180 ?

All the arrays contain numbers. I want to expand the 1x140 array to a 1x180 array by means of interpolation.

In a simplified form, it should be something like this:

A = [1 5 7 8 3]
B = [1 3 5]

result= 

[1 5 7 8 3

1 2 3 4 5]

The array B (1x3) is expanded to an 1x5 matrix. And the values in between are interpolated.

Basically, I thought of using "vertcat" after all arrays are expanded by a same amount of columns.

Thanks in advance, Koen

Upvotes: 0

Views: 185

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

How about this?

array = {[1 5 7 8 3],[1 3 5]}; % example data
N = 5; % desired length (180 in your case)

aux = cellfun(@(v) interp1(linspace(0,1,length(v)),v,linspace(0,1,N)), array, 'uni', false);
result = cat(1,aux{:});

It uses linear interpolation. For your example, this gives

>> result

result =

     1     5     7     8     3
     1     2     3     4     5

Note that linear interpolation modifies all values of the vector except first and last, in general. For example, with N=5 the vector [1 3 4 5] would get interpolated to [1 2.5 3.5 4.25 5]. You could use other forms of interpolation by passing an extra argument to interp1, see help interp1.

Upvotes: 3

Related Questions