MATLAB: How to create an empty struc with fields of a given struct

struct

I have a struct A with many fields:
A.a
A.b
...
A.z
Now I want to create a struct B, with the same fields:
B.a
B.b
...
B.z
With
B=struct(A)
B has also the same size as A, and all values of A are also included. But I want to have an empty struct with 0x1 dimension.
Background: in a loop I want to sort out some entries of A, that fit a certain criteria and write it into B. If I do
B=struct([])
B(n)=A(m)
then the structs do not match. Therefore I want to create B in advance and then assign it.

Best Answer

One way, which will give you a 0x0 struct, is:
f = fieldnames(A)';
f{2,1} = {};
B = struct(f{:});
Method basically obtained from this FEX submission by David Young:
CAUTION: From the description you give, it sounds like you will be dynamically increasing the size of B inside a loop. That will cause repeated copying that will slow down performance. If the number of elements of B turns out to be small, then no big deal. But if the number of elements of B turns out to be large, then you might experience a performance drag. In that case it might make sense to preallocate a size for B at the start (instead of 0x0) that is large enough to hold all the results, and then lop off the tail that you don't need after the loop is done.