How can I access part of my stucture by index?

2 ビュー (過去 30 日間)
bkshn
bkshn 2015 年 2 月 13 日
編集済み: Stephen23 2015 年 2 月 14 日
Hello
I have a structure like bellow
x.part1.vector=3;
x.part1.cost=4;
x.part2.vector=5;
x.part2.cost=6;
x.part3.vector=7;
x.part3.cost=8;
I want to access value of vector on part (for example 3).
How can I access this by index?
thanks for your help

採用された回答

Image Analyst
Image Analyst 2015 年 2 月 13 日
bkshn, try this and see if it's what you want:
% Define an array of structures.
x(1).vector=3;
x(1).cost=4;
x(2).vector=5;
x(2).cost=6;
x(3).vector=7;
x(3).cost=8;
% Access "part 3" with an index
index = 3;
output = x(index).vector
% Sum all "vector" fields for all indexes ("parts"):
outputSum = sum([x.vector])

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 2 月 13 日
編集済み: Stephen23 2015 年 2 月 14 日
What you have defined is a scalar structure. This does not support indexing because there is only one structure element. You can access the data only using the fieldnames.
If you wish you use indexing, then you can create a non-scalar structure, which you can then use indexing with. There a multiple ways to create a non-scalar structure . Here are two ways of creating the same non-scalar structure:
>> A(1).data = 4;
>> A(2).data = 5;
>> A(3).data = 6;
OR
>> A = struct('data',{4,5,6});
And then access the field of any element of the structure using indexing and the fieldname:
>> A(2).data
ans = 5
Which means you can get the sum of all of the elements using this simple code:
>> sum([A.data])
ans = 15
  1 件のコメント
bkshn
bkshn 2015 年 2 月 13 日
I do it because I want to have a vector and the sum of its value in a structure.
then I want to select the vector with minimume sum of value.
I think I can't do it by your example. Am I right?

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

カテゴリ

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