add new row to table with missing values

조회 수: 46 (최근 30일)
Amirali Kamalian
Amirali Kamalian 2022년 1월 18일
댓글: KSSV 2022년 1월 18일
How can I add a new row to an existing table with missing values?
For illustration, I define a table T with 4 variables: name, city, age, height.
V.name = "Ann";
V.city = "Berlin";
V.age = 24;
V.height = 172;
T = struct2table(V);
Now, I want to add another row to this table where the new row only contains values for 3 of the variables (out of 4).
V2.name = "Luka";
V2.city = "Tokyo";
V2.age = 30;
T = [T; struct2table(V2)];
All tables being vertically concatenated must have the same number of variables.
This leads to the following error:
"All tables being vertically concatenated must have the same number of variables."
What's the best practice for such situations?

답변 (1개)

KSSV
KSSV 2022년 1월 18일
V.name = "Ann";
V.city = "Berlin";
V.age = 24;
V.height = 172;
T1 = struct2table(V);
V2.name = "Luka";
V2.city = "Tokyo";
V2.age = 30;
T2 = struct2table(V2);
T2.height = NaN ;
T = [T1;T2]
T = 2×4 table
name city age height ______ ________ ___ ______ "Ann" "Berlin" 24 172 "Luka" "Tokyo" 30 NaN
  댓글 수: 4
Amirali Kamalian
Amirali Kamalian 2022년 1월 18일
In each sequence of a for loop, a new row is added to the table. The values for the new row are collected in a struct and then struct2table is called to update the table with a new row.
Are you suggesting to collect all the data in a struct array and then convert that to a table in a single struct2table call? Does that give more flexibility in terms of "missing" values?
KSSV
KSSV 2022년 1월 18일
YEs exactly. That makes your life very easy.
V = struct ;
V(1).name = "Ann";
V(1).city = "Berlin";
V(1).age = 24;
V(1).height = 172;
V(2).name = "Luka";
V(2).city = "Tokyo";
V(2).age = 30;
T = struct2table(V)
T = 2×4 table
name city age height ______ ________ ___ ____________ "Ann" "Berlin" 24 {[ 172]} "Luka" "Tokyo" 30 {0×0 double}

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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by