Reputation: 28655
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.
Upvotes: 2
Views: 2520
Reputation: 125874
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
Upvotes: 6
Reputation: 34621
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.
Upvotes: 2