Asked by Daniel
on 21 Apr 2012

Hello,

I was wondering if MATLAB had a function for doing the following. Say I have the following vector:

[1 1 2 2 0 0]

And I want to make a new vector which contains 1.5 times the amount of the present elements, i.e. "stretch" it by 1.5

[1 1 1 2 2 2 0 0 0]

Just asking before writing any buggy, inneficient code.

regards,

Daniel

*No products are associated with this question.*

Answer by Andrei Bobrov
on 21 Apr 2012

a = [1 1 2 2 0 0]; t = 1.5

k=[true,diff(a)~=0]; k2 = find(k); k3 = [k2(2:end)-1 numel(k)]; k4 = k3-k2+1; m = round(k4*t); if all(diff(m) == 0) out = reshape(ones(m(1),1)*a(k),1,[]); else out = cell2mat(arrayfun(@(x,y)x(ones(1,y)),a(k),m,'un',0)); end

**ADD** on Walter's comment

out = kron(a(1:2:end),ones(1,t*2))

Answer by Image Analyst
on 21 Apr 2012

Daniel, if you have the Image Processing Toolbox, you can do it in one single, and *very* simple, line of code:

% Create sample data. m1 = [1 1 2 2 0 0] % Now do the replication like Daniel wants. m2 = imresize(m1, [1 9], 'nearest')

In the command window:

m1 = 1 1 2 2 0 0 m2 = 1 1 1 2 2 2 0 0 0

Of course you can change the 9 to be any length you want your output vector to be.

Answer by Richard Brown
on 21 Apr 2012

Further to Image Analyst's answer, you can do it without the image processing toolbox too (assuming m has an even number of entries)

m = [1 1 2 2 0 0 ]; n = numel(m); m2 = interp1(1:n, m, linspace(1, n, 1.5*n), 'nearest')

Opportunities for recent engineering grads.

## 2 Comments

## James Tursa (view profile)

Direct link to this comment:http://au.mathworks.com/matlabcentral/answers/36144#comment_74941

Is it always adding one more element of each? Or by "1.5 times" do you mean that you have a larger problem in mind like [1 1 1 1 2 2 2 2 0 0 0 0] etc and would like the solution to be [1 1 1 1 1 1 2 2 2 2 2 2 0 0 0 0 0 0] etc? I.e., how generic is your real problem?

## Walter Roberson (view profile)

Direct link to this comment:http://au.mathworks.com/matlabcentral/answers/36144#comment_74945

Will the number of identical elements in a row always be the same?