MATLAB: How do you call data from a structure array in a function

file instructure array

Hey all,
I'm new to MATLAB (and programming) and I have a question about how to call data stored in a structure array in a function. For a little bit of background, I have a bunch of related data stored in a scalar structure array I've named 'Data' with fields named f1, f2, f3 and so on that all contain 2×2 matrices.
To plot data from any of these fields seems simple enough, it's just (for example):
plot(Data.f1(:,1), Data.f1(:,2))
What I want to do now is create a function where the input(s) of the function dictate which of these fields are plotted. Thus, if the input variable of the function is x then the corresponding matrix to be plotted should be something like
plot(Data.f_x(:,1), Data.f_x(:,2))
However, when I try this is it obvious that MATLAB has no idea that x is supposed to be a variable. And the text in the function parenthesis isn't really a string (I guess) because I have tried using num2str() and sprintf() functions to try and get around this like
plot(Data.f_num2str(x)(:,1), Data.f_num2str(x)(:,2))
This just looks plain wrong to me, but I don't know enough to know why. Any help would be greatly appreciated.

Best Answer

Part One: Dynamic Fieldnames
This is called dynamic fieldnames, and the syntax is pretty simple: you just need to add some parentheses:
Data.(str)
where str is a variable that defines the name of that field. In your case you could generate the field name using sprintf:
tmp = Data.(sprintf('f%d',x));
plot(tmp(:,1),tmp(:,2)
Part Two: Using Non-Scalar Structures Instead
Although there might be a good reason for your naming, these sequentially-numbered names might be better replaced by a non-scalar structure. These would allow you to simply call each element without needing to generate the fieldname dynamically:
tmp = Data(x).field;
plot(tmp(:,1),tmp(:,2)
which you can see is much simpler to work with! This also has the advantage that you can do neat tricks like this:
Data.field
returns a list of all field values, in a comma-separated list. This means, for example, that you can create a cell array of all field values simply by doing this:
{Data.field}
or concatenate them into one array like this:
[Data.field]
Part Three: Use a Cell/Numeric Array Instead
If this is the only data that is being stored in the structure, then using a structure to store it is very large hammer to crack this nut with: it would be simpler to use either:
  • one cell array, and each cell contains one matrix
  • one simple numeric array, using the dimensions to distinguish the semantic meaning (e.g. the third dimension corresponds to different data measurements).