2

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.

gnovice
  • 125,304
  • 15
  • 256
  • 359
second
  • 28,029
  • 7
  • 75
  • 76

3 Answers3

10

Put square brackets around the expression, i.e.

[w(1:2).bytes]
Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
6

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
  • 125,304
  • 15
  • 256
  • 359
2

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
  • 34,255
  • 14
  • 110
  • 165
  • The code above will throw an error if the strings are not the same length. You should use STRVCAT in such a case. – gnovice Jul 14 '09 at 14:24