Insert new row with values in a table before specific values
古いコメントを表示
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!
採用された回答
その他の回答 (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
カテゴリ
ヘルプ センター および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!