2

I want to get a value from a structure array by code, and I'll have the index stored in a string.

I've tried to run this code:

function M = getdata(matrix,field,varargin)
exp = [];
for i = 1:nargin-3
    exp = [exp num2str(varargin{i}) ','];
end
exp = [exp num2str(varargin{nargin-2})];
M = eval('matrix(exp).(Field)');
end

However, it fails.

For example, suppose I have a structure array with 2 fields, A and B. So, I could write

MyStruct(1,1).A 

A possible use would be:

M = getdata(MyStruct,A,1,1) 

and I want the program to do:

M = MyStruct(1,1).A

How could I do that?

Thanks!

2
  • 2
    ...Why not just do M = matrix(varargin{:}).(field)? Commented Nov 14, 2013 at 14:30
  • Because I really want to use getdata with something like: M = getdata(MyStruct,A,1,:) and, if I use the expression you say, I only get one value, not a vector. Commented Nov 14, 2013 at 15:38

2 Answers 2

2

You can use the getfield function:

M = getfield(MyStruct, {1,1} ,'A');

Or if you wanted, say, MyStruct(1,1).A(3).B:

M = getfield(MyStruct, {1,1}, 'A', {3},'B');
Sign up to request clarification or add additional context in comments.

1 Comment

It fails when one of the indices is :.
0

For the example you give, this will suffice:

function M = getdata(matrix,field,varargin)
    M = matrix(varargin{:}).(field);

which you call like

getdata(myStruct, 'A', 1,1)

which makes that function pretty useless.

But, in general, when you have indices given as strings, you can follow roughly the same approach:

%// Your indices
str = {'1', '2'};

%// convert to numbers
str = cellfun(@str2double, str, 'UniformOutput', false);

%// use them as indices into structure
M = myStruct(str{:}).(field)

And if you really insist, your call to eval is just wrong:

M = eval(['matrix(' exp ').(' field ')']);

And, as a general remark, please refrain from using exp as the name of a variable; it is also the name of a built-in function (the natural exponential function).

1 Comment

Thank you. Unfortunately, none of the solutions given are useful for me. What I really want to do is using :as index. cellfun is also useless because the conversion from string to cell returns NaN.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.