insert row into table

131 次查看(过去 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?

采纳的回答

Walter Roberson
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 个评论
amateurintraining
amateurintraining 2017-11-20
That worked swimmingly. Thank you. How could I code it if NewBValue should be the interpolation between the above value and below value? I'm sorry if it's not very clear but essentially:
NewBValue= 20000+[(15000-20000)/(120-0)]*(90-0)
I'm trying to use the function interp1 but I don't quite understand it.
Walter Roberson
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
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 CenterFile Exchange 中查找有关 Graphics Object Properties 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by