views:

590

answers:

3

The output of eg >>w = whos; returns an array of structs. I would like to construct an array whose elements are the scalars from a particular field name in each struct.

The most obvious way of doing this doesn't return an array as I want, but each answer separately.

>> w(1:2).bytes
ans =
    64
ans =
   128

I could do it with a loop, but was wondering if there's a nicer way.

+7  A: 

Put square brackets around the expression, i.e.

[w(1:2).bytes]
Mr Fooz
beautiful, thanks!
second
+1  A: 

In situations like these, using cat is more general purpose. Suppose you wanted to do the same with a bunch of strings, then the [ ] method wouldn't work, and you'd have to use:

cat(1,w(1:2).class)

And in the case above,

cat(1,w(1:2).bytes)

Additionally, you'd want to keep things as columns in MATLAB for better performance.

Jacob
The code above will throw an error if the strings are not the same length. You should use STRVCAT in such a case.
gnovice
Thanks! I'll keep that in mind.
Jacob
+4  A: 

Accessing a field for an array of structures will return as an output a comma-separated list (or CSL). In other words, the output from your example:

w(1:2).bytes

is equivalent to typing:

64, 128

As such, you can use the output in any place where a CSL could be used. Here are some examples:

a = [w(1:2).bytes];         % Horizontal concatenation = [64, 128]
a = horzcat(w(1:2).bytes);  % The same as the above
a = vertcat(w(1:2).bytes);  % Vertical concatenation = [64; 128]
a = {w(1:2).bytes};         % Collects values in a cell array = {64, 128}
a = zeros(w(1:2).bytes);    % Creates a 64-by-128 matrix of zeroes
b = strcat(w.name);         % Horizontal concatenation of strings
b = strvcat(w.name);        % Vertical concatenation of strings
gnovice