insert row into table
138 次查看(过去 30 天)
显示 更早的评论
Hi. I want to make a function. This function has the input a table and a new value. How do I insert the new value into the table such that it is in order. I'm sorry if that is confusing but for example: I have a table:
a b
0 20000
120 15000
160 17000
200 19000
And I want to insert a new row where a=90. How do I do this if the provided function is already in order?
0 个评论
采纳的回答
Walter Roberson
2017-11-18
mask = YourTable.a < 90;
newa = [YourTable.a(mask); 90; YourTable.a(~mask)];
newb = [YourTable.b(mask); NewBValue; YourTable.b(~mask)];
YourTable{:,[1 2]} = [newa, newb];
2 个评论
Walter Roberson
2017-11-20
interp_at = 90;
mask = YourTable.a < interp_at;
a_before = YourTable.a(mask);
a_after = YourTable.a(~mask);
b_before = YourTable.b(mask);
b_after = YourTable.b(~mask);
NewBvalue = interp1([a_before(end), a_after(1)], [b_before(end), b_after(end)], interp_at);
new_a = [a_before; interp_at; a_after];
new_b = [b_before; NewBValue; b_after];
YourTable{:,[1 2]} = [new_a, new_b];
However, you would probably find it much easier to adopt a modification of the technique that Akira Agata showed:
interp_at = 90;
new_a = [YourTable.a; interp_at];
new_b = interp1( YourTable.a, YourTable.b, new_a );
YourTable{:,[1 2]} = sortrows( [new_a, new_b] );
You can specify multiple locations in interp_at, as long as you make it a column vector.
更多回答(1 个)
Akira Agata
2017-11-18
How about concatenate 2 tables, and then sort it? Here is an example:
% Initial table
T = table(...
[0;120;160;200],...
[20000;15000;17000;19000],...
'VariableNames',{'a','b'});
% Additional data
T1 = table(90,19000,...
'VariableNames',{'a','b'});
% Concatenate and sort
Tout = [T;T1];
Tout = sortrows(Tout,'a');
The output is:
>> Tout
Tout =
5×2 table
a b
___ _____
0 20000
90 19000
120 15000
160 17000
200 19000
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Properties 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!