Put nested structure into another structure

10 ビュー (過去 30 日間)
Devin Kim
Devin Kim 2020 年 1 月 31 日
コメント済み: Devin Kim 2020 年 2 月 1 日
Below I have a function that returns a struct ( my actual code has many functions as methods in an object that return similar data).
function out = get_results1
mystruct.name = "result1";
mystruct.value = 23;
mystruct.unit = 'mph';
out = mystruct;
end
However I have some functions that return more than one result.. for example:
function out = get_results2
mystruct.name = {"result1"; "result2"};
mystruct.value = {23; 34 };
mystruct.unit = 'mph';
out = mystruct;
end
My goal is to comebine the results of all of these functions into a table like the following:
a = get_results1();
b = get_results2();
combined = [a, b];
mytable = struct2table(combined);
however this will not work because of inconsistent sizes... Could someone tell me the following:
1) Should I restructure my functions to provide a different output?
2) Is there another way pull out the nested structures from the functions that have multiple results?

採用された回答

Steven Lord
Steven Lord 2020 年 1 月 31 日
Why not go directly to a table array?
a = maketable("result1", 23, "mph");
b = maketable(["result1"; "result2"], [23; 34], ["mph"; "mph"]);
c = [a; b]
function T = maketable(name, value, unit)
T = table(name, value, unit);
end
You could be a little more sophisiticated and avoid the need to duplicate the units by checking inside maketable if you need to repmat one or more of the variables (for scalar expansion) or you could call maketable more frequently.
a = maketable("result1", 23, "mph");
b = [a; maketable("result1", 23, "mph")];
c = [b; maketable("result2", 34, "mph")]
function T = maketable(name, value, unit)
T = table(name, value, unit);
end
  1 件のコメント
Devin Kim
Devin Kim 2020 年 2 月 1 日
I ended up just doing this in my functions:
function out = myfunc()
result1.name = "name1";
result2.name = "name2";
result1.value = 23;
result2.value = 24;
out = [result1, result2];
However I think your answer is a good alternative as well! Thanks. I am now having trouble putting my table into a UI table... but I'll dig in to that on my own some more.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by