Insert Zeros (m -rows) in an existing Matrix every n-rows in an efficient way
    6 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Tim
 el 6 de En. de 2014
  
    
    
    
    
    Comentada: Jorge Ignacio Cisneros Saldana
 el 10 de Mayo de 2018
            I've data like this (the actualy matrix is much bigger)
A =
     1     1
     2     2
     3     3
     4     4
     5     5
     6     6
     7     7
     8     8
     9     9
    10    10
    11    11
    12    12
Let's say I want to insert 2 rows of zeros (m=2, zeros(2,2)) every 3 lines (n=3), so that the result would be:
A =
     1     1
     2     2
     3     3
     0     0
     0     0
     4     4
     5     5
     6     6     
     0     0
     0     0
     7     7
     8     8
     9     9
     0     0
     0     0
    10    10     
    11    11
    12    12
     0    0
     0    0
Is there a quick way to do it? Online I found the "insertrows"-function but that didn't work... Thanks a lot in advance!
0 comentarios
Respuesta aceptada
  Azzi Abdelmalek
      
      
 el 6 de En. de 2014
        [n,m]=size(A)
B=permute(reshape(A',m,3,[]),[2 1 3]);
p=size(B,3)
C=[B;zeros(2,m,p)]
out=reshape( C(:,:),[],m,1)
2 comentarios
  Jorge Ignacio Cisneros Saldana
 el 9 de Mayo de 2018
				The result is wrong
1 7 2 8 3 9 0 0 0 0 1 7 2 8 3 9 0 0 0 0 4 10 5 11 6 12 0 0 0 0 4 10 5 11 6 12 0 0 0 0
Más respuestas (2)
  Andrei Bobrov
      
      
 el 6 de En. de 2014
        
      Editada: Andrei Bobrov
      
      
 el 6 de En. de 2014
  
      m = 3;
k = 2;
n = size(A);
out = reshape([reshape(A,m,[]);zeros(k,n(1)/m*n(2))],[],n(2));
or
m = 3;
k = 2;
n = size(A);
c = ones(1,n(2));
t = rem((0:n(1)*(k/m+1)-1)',m+k)+1 <= m;
out = t*c
out(t(:,c)) = A;
1 comentario
  Jos (10584)
      
      
 el 6 de En. de 2014
        % data
A = cumsum(ones(12,2),1) % as above
n = 3 ;
m = 2 ;
% engine
B = insertrows(A,0,repmat(n:n:size(A,1),m,1))
btw, I am the author of this function, so I might be a little biased ;-)
3 comentarios
  Jos (10584)
      
      
 el 6 de En. de 2014
				The trick is to use the same insertion location multiple times. I acknowledge that this might be a little unclear when reading the documentation.
  Jorge Ignacio Cisneros Saldana
 el 9 de Mayo de 2018
				It does not work error
Error in Insertzeros (line 30) B = insertrows(A,0,repmat(n:n:size(A,1),m,1));
Ver también
Categorías
				Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




