简体   繁体   中英

Dynamically create numeric matrix from fields of a scalar structure

in Matlab, I have a scalar structure S with some fields. Each field contains a numeric vector, and all these vectors have the same size, say nx1 .

Now I would like to create a numeric matrix based on a selection of the fields.

The starting point is a logical mask sized mx1 , where m is the number of fields of S . mask(i) is true if the ith field of S should be included in the matrix. So the matrix size would be nx sum(mask) .

Example (in my code, the structure is not built in this way, of course :-)

vec = rand(1000,1);
S.f1 = vec;
S.f2 = vec;
S.f3 = vec;
S.f4 = vec;
S.f5 = vec;

mask = [false true true false false]; % 5 elements because S has 5 fields

The expected output would be:

output = [S.f2 S.f3];

But of course, the creation of output should depend dynamically on the fields of S and on mask .

Is there any way to achieve this without using an ugly construction including a filter of the struct field names, loop, etc.?

Thank you very much!

Philip

Here's one way -

fns = fieldnames(S) %// Get all fieldnames
S = rmfield(S,fns(~mask)) %// Remove all fields with masking values as false

Next, to get your numeric array, use struct2array -

output = struct2array(S)

You can convert the struct into a cell using struct2cell , and use normal cell indexing to get the fields you want.

a = (1:5).';
s.f1 = a; s.f2 = 2*a; s.f3 = 3*a; s.f4 = 4*a; s.f5 = 5*a;
c = struct2cell(S);
[c{mask}]  
ans =

     2     3
     4     6
     6     9
     8    12
    10    15

You can do something like:

msks = fieldnames(S);
msks = msks(mask);
n = numel(msks);
output = zeros(1000,n);
for i = 1:n
    output(:,i) = S.(msks{i});
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM