필터 지우기
필터 지우기

insert row into table

조회 수: 96 (최근 30일)
amateurintraining
amateurintraining 2017년 11월 18일
댓글: amateurintraining 2017년 11월 20일
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
  댓글 수: 1
amateurintraining
amateurintraining 2017년 11월 20일
Thank you very much for your answer.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by