Insert new row with values in a table before specific values
    조회 수: 22 (최근 30일)
  
       이전 댓글 표시
    
Hey,
I have a table with 3 columns containing the following values:

Now I want to insert a new row with (0,0,0) everytime WP1 hits 0 before that, so that the new table looks like that:

What is an efficient way to do that?
Thanks for your help!
댓글 수: 0
채택된 답변
  Yazan
      
 2021년 8월 9일
        WP1 = [0 145 169 1693 1708 2729 0 48];
WP2 = [145 169 1693 1708 2729 2779 48 1382];
WC = [0 1 1 1 1 0 0 1];
dat = [WP1', WP2', WC'];
T = table(WP1', WP2', WC', 'VariableNames', {'WP1', 'WP2', 'WC'});
disp(T)
idx = find(T.WP1 == 0);
idx = idx + (0:length(idx)-1)';
Idx = true(size(WP1') + [length(idx) 0]);
Idx(idx) = false;
dat2 = zeros(size(dat) + [length(idx), 0]);
dat2(Idx, :) = dat;
T2 = table(dat2(:,1), dat2(:,2), dat2(:,3), 'VariableNames', {'WP1', 'WP2', 'WC'});
disp(T2)
추가 답변 (1개)
  Peter Perkins
    
 2021년 8월 9일
        It is possible to just use tabular subscripting to insert these rows. This is kind of old school MATLAB. Don't know if it is easier or harder to understand.
>> WP1 = [0; 145; 169; 1693; 1708; 2729; 0; 48];
>> WP2 = [145; 169; 1693; 1708; 2729; 2779; 48; 1382];
>> WC = [0; 1; 1; 1; 1; 0; 0; 1];
>> T = table(WP1, WP2, WC)
T =
  8×3 table
    WP1     WP2     WC
    ____    ____    __
       0     145    0 
     145     169    1 
     169    1693    1 
    1693    1708    1 
    1708    2729    1 
    2729    2779    0 
       0      48    0 
      48    1382    1 
Create an index vector that puts existing rows at their new locations.
>> n = height(T);
>> i = (1:n)';
>> incr = zeros(size(i));
>> incr(j) = 1;
>> i2 = i + cumsum(incr)
i2 =
     2
     3
     4
     5
     6
     8
    10
    11
Create an index vector that puts the inserted rows at their new locations.
>> j = find(T.WC == 0);
>> incr = ones(size(j)); incr(1) = 0;
>> j2 = j + cumsum(incr)
j2 =
     1
     7
     9
Add a row at the end, merge the index vectors, and use that to insert copies of the new end row into the right places.
>> T{end+1,:} = [0 0 0];
>> [~,k] = sort([i2; j2]);
>> k(j2) = n+1;
>> T = T(k,:)
T =
  11×3 table
    WP1     WP2     WC
    ____    ____    __
       0       0    0 
       0     145    0 
     145     169    1 
     169    1693    1 
    1693    1708    1 
    1708    2729    1 
       0       0    0 
    2729    2779    0 
       0       0    0 
       0      48    0 
      48    1382    1 
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


