Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Matlab field inside a struct from C#

Tags:

c#

matlab

Assume the following in Matlab:

%variable info contains a <1x2 struct>, so...
info(1,1);
info(1,2);

%these contains fields like .a .b etc.
info(1,1).a = [1, 2, 3, 4, etc... ];
info(1,2).b = [1, 2, 3, 4, etc... ];

Now in C#:

Normally, I would do something like:

//assume I received the variable info from an output parameter
//of a MatLab function, called via InterOp
MWNumericArray fieldA = (MWNumericArray) info.GetField("a");

//Remember that info contains 1row with 2 columns

I want to access the fields from both columns

//this is what i've tried, and failed, with  the exception for data["a",1]
MWNumericArray fieldA = (MWNumericArray) data["a", 0];
MWNumericArray fieldA = (MWNumericArray) data["a", 1, 1];
MWNumericArray fieldA = (MWNumericArray) data[0];

So how do I access a field from inside a nameless struct ?

While step debugging, VisualStudio defines info as a

info = { 1x2 struct array with fields: a b }
like image 810
Terence Avatar asked Nov 29 '13 23:11

Terence


People also ask

How do you access a field in a struct?

Accessing data fields in structs Although you can only initialize in the aggregrate, you can later assign values to any data fields using the dot (.) notation. To access any data field, place the name of the struct variable, then a dot (.), and then the name of the data field.

How do I extract a field from a structure in MATLAB?

Extract Fields From Structurehold on plot(extractfield(roads,'X'),extractfield(roads,'Y')); plot(extractfield(r,'X'),extractfield(r,'Y'),'m'); Extract the names of the roads, stored in the field STREETNAME . The field values are character vectors, so the result is returned in a cell array.

How do you read a value from a struct in MATLAB?

value = getfield( S , field ) returns the value in the specified field of the structure S . For example, if S.a = 1 , then getfield(S,'a') returns 1 . As an alternative to getfield , use dot notation, value = S.

How do you check if a struct has a field MATLAB?

To determine if a field exists in a particular substructure, use 'isfield' on that substructure instead of the top level. In the example, the value of a.b is itself a structure, and you can call 'isfield' on it. Note: If the first input argument is not a structure array, then 'isfield' returns 0 (false).


1 Answers

Solved by using:

MWNumericArray fieldA = (MWNumericArray) data["a", 1]; //data(1,1).a
MWNumericArray fieldB = (MWNumericArray) data["b", 1]; //data(1,1).b
fieldA = (MWNumericArray) data["a", 2]; //data(1,2).a
fieldB = (MWNumericArray) data["b", 2]; //data(1,2).b

Remember mathematicians count from 1, programmers from 0.

like image 156
Terence Avatar answered Oct 20 '22 15:10

Terence