increase the length of a martix every 5 rows

Dear all,
I have a matrix (double array) of dimension 40000 by 7 and I want to increase the length of this matrix every 5 rows by adding a cell NaN.
For instance, if I have initially
A=[2.4332 4.1477;
2.6073 4.5900;
2.2310 3.7442;
2.4555 4.1178;
2.5096 4.1946;
2.7517 4.7802;
2.8372 4.9423;
2.9577 5.1563;
3.2365 5.6061;
3.0658 5.3787;
2.9244 5.0497;
2.6104 4.4623;
2.5419 4.4164;
2.4947 4.3577;
2.5633 4.7050
]
then I want
A=[2.4332 4.1477;
2.6073 4.5900;
2.2310 3.7442;
2.4555 4.1178;
2.5096 4.1946;
NaN NaN
2.7517 4.7802;
2.8372 4.9423;
2.9577 5.1563;
3.2365 5.6061;
3.0658 5.3787;
NaN NaN
2.9244 5.0497;
2.6104 4.4623;
2.5419 4.4164;
2.4947 4.3577;
2.5633 4.7050;
NaN NaN
]
I am looking for an efficient code (1-2 lines if possible)
thank you very much

 Réponse acceptée

Oleg Komarov
Oleg Komarov le 5 Août 2012
The efficient code:
[r,c] = size(A);
add = floor(r/5);
Anew = NaN(r + add,c);
idx = (1:r) + reshape(repmat(0:add-1,5,1),1,r);
Anew(idx,:) = A;
The two line code:
Anew = NaN(size(A,1) + size(A,1)/5,size(A,2));
Anew((1:size(A,1)) + reshape(repmat(0:floor(size(A,1)/5)-1,5,1),1,size(A,1)),:) = A;

7 commentaires

antonet
antonet le 5 Août 2012
Modifié(e) : antonet le 5 Août 2012
Hi Oleg,
Which of the two is faster?
thanks
Walter Roberson
Walter Roberson le 5 Août 2012
When I test, using a 40000 x 7 array, the two versions are the same speed to within measurement error.
d = 5;
m = size(A,1);
k = m + floor(m/d);
Aout = nan(k,2);
Aout(~~rem(1:k,d+1),:) = A;
antonet
antonet le 5 Août 2012
thanks Andrei!
Slightly corrected version of Andrei's code, expressed as a function:
function Aout = answer45305_3(A)
d = 5;
m = size(A,1);
k = m + floor(m/d);
Aout = nan(k,size(A,2));
Aout(~~rem(1:k,d+1),:) = A;
end
My tests indicate that this is just shy of 3 times slower than Oleg's versions.
Matt Fig
Matt Fig le 5 Août 2012
Modifié(e) : Matt Fig le 5 Août 2012
I'll take a stab at it.
function Anew = insert_nansmatt(A,x)
% Insert a row of nans in A every x rows.
% A need not have mod(size(A,1),x)==0.
[R,C] = size(A);
S = R + floor(R/x);
Anew = nan(S,C);
idx1 = true(S,1);
idx1(x+1:(x+1):S) = false;
Anew(idx1,:) = A;
Azzi Abdelmalek
Azzi Abdelmalek le 5 Août 2012
i like this one

Connectez-vous pour commenter.

Plus de réponses (1)

Azzi Abdelmalek
Azzi Abdelmalek le 5 Août 2012
Modifié(e) : Walter Roberson le 5 Août 2012
% this code is for test the example
B=reshape(A,5,2,3);B(6,:,:)=nan;result= reshape(B,18,2)
% this code is for your real data
B=reshape(A,5,7,1400);B(6,:,:)=nan;result= reshape(B,8400,7)
% note that 1400 = 7000/5; and 8400=(5+1)*1400

Catégories

En savoir plus sur Large Files and Big Data dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by