Adding fields of two different structs together

% Example structures:
part(1) = struct('name', 'x', 'number', 1);
part(2) = struct('name', 'y', 'number', 2);
part(3) = struct('name', 'z', 'number', 3);
% Example: 1st user input should be the 'name' so "x"
% 2nd user input should be another'name' so "z"
% total_number = 1 + 3

3 件のコメント

VBBV
VBBV 2023 年 5 月 13 日
移動済み: VBBV 2023 年 5 月 13 日
part(1) = struct('name', 'x', 'number', 1)
part = struct with fields:
name: 'x' number: 1
part(2) = struct('name', 'y', 'number', 2);
part(3) = struct('name', 'z', 'number', 3);
part(1).number+part(3).number
ans = 4
Kono
Kono 2023 年 5 月 13 日
移動済み: VBBV 2023 年 5 月 13 日
Thanks for the response but is there a way to make it depend on the user's input?
For example I would like the user to input two names, say 'y' and 'z', and then come up with the sum of numbers
Stephen23
Stephen23 2023 年 5 月 13 日
" is there a way to make it depend on the user's input?"
part = struct("x",1,"y",2,"z",3);
part.("x")+part.("z")
ans = 4

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

 採用された回答

Matt J
Matt J 2023 年 5 月 13 日

0 投票

It would be a better to use a dictionary than a struct,
part=dictionary(["x","y","z"],1:3);
part("x")+part("z")
ans = 4

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

質問済み:

2023 年 5 月 13 日

コメント済み:

2023 年 5 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by