How to put together variables(matrix, vector etc..) with different type of size.

2 ビュー (過去 30 日間)
JaeJun Lee
JaeJun Lee 2015 年 1 月 5 日
回答済み: Guillaume 2015 年 1 月 5 日
Hello, Is there any way to make variables,with different types or sizes, contained in one place.
I thought 'struct' is ok, but I need to access members with index.
'robot_state' is struct variable and have 3 fields, 'position','velocity','acceleration'.
But it cannot be accessed by index as far as I know.
For example, I cannot access 'velocity' field, with the expression like 'robot_state[2]'.
Guys, is there any way to solve this?
thank you very much.

回答 (2 件)

Doug
Doug 2015 年 1 月 5 日
robot_state = struct('position',{'top','bottom'}, 'velocity',{10,20}, 'acceleration',{0.1,0.3});
>> robot_state(2)
ans =
position: 'bottom'
velocity: 20
acceleration: 0.3000
>> robot_state(2).velocity
ans =
20

Guillaume
Guillaume 2015 年 1 月 5 日
To make variables,with different types or sizes, contained in one place use a cell array.
robot_state = {'bottom', 20, 0.3};
robot_state{2}
ans =
20
You can convert a structure into a cell array with struct2cell:
robot_state = struct('position', 'bottom', 'velocity', 20, 'acceleration', 0.3);
c = struct2cell(robot_state);
c{2}
ans =
20
Another option is to use dynamic field names with fieldnames:
robot_state = struct('position', 'bottom', 'velocity', 20, 'acceleration', 0.3);
fn = fieldnames(robot_state);
robot_state.(fn{2})
ans =
20
I'm not sure why you want to use numeric indices to access the fields of a structure, though. What's wrong with using the field name which is a lot easier to understand than an arbitrary meaningless number. robot_state.velocity is a lot clearer (i.e. less bugs) than robot_state{2}.

カテゴリ

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