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

1 Ansicht (letzte 30 Tage)
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.

Antworten (2)

Doug
Doug am 5 Jan. 2015
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 am 5 Jan. 2015
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}.

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by