structure=structcut(structure,i) I find I often want to shrink a structure of the form s.a(n) s.b(n) s.c(n) according to some matrix of indices i. For example it's a pain to do: x=s.a>1; s.a=s.a(x); s.b=s.b(x); s.c=s.c(x); and if I add another field I have to change the code in multiple places. This function automatically cuts all fields so the code becomes: x=s.a>1; s=structcut(s,x); and continues to work if fields are added. Now extended so that fields can be 2D - will try to figure out which dimension to cut over by looking for the dim which is equal length for all fields. If all are same cut will occur over rows.
0001 function s=structcut(s,x) 0002 % structure=structcut(structure,i) 0003 % 0004 % I find I often want to shrink a structure 0005 % of the form 0006 % 0007 % s.a(n) 0008 % s.b(n) 0009 % s.c(n) 0010 % 0011 % according to some matrix of indices i. 0012 % For example it's a pain to do: 0013 % 0014 % x=s.a>1; 0015 % s.a=s.a(x); 0016 % s.b=s.b(x); 0017 % s.c=s.c(x); 0018 % 0019 % and if I add another field I have to change 0020 % the code in multiple places. 0021 % 0022 % This function automatically cuts all fields 0023 % so the code becomes: 0024 % 0025 % x=s.a>1; 0026 % s=structcut(s,x); 0027 % 0028 % and continues to work if fields are added. 0029 % 0030 % Now extended so that fields can be 2D - will try to figure 0031 % out which dimension to cut over by looking for the dim which is 0032 % equal length for all fields. If all are same cut will occur over 0033 % rows. 0034 0035 % first let's check if it even needs to be cut. 0036 if(length(x)==1) 0037 if(x==0) 0038 s = []; 0039 else 0040 s = s; 0041 end 0042 return; 0043 end 0044 0045 names=fieldnames(s); 0046 0047 % Get sizes of fields 0048 for i=1:length(names) 0049 d(i,:)=size(getfield(s,char(names(i)))); 0050 end 0051 0052 if(all(d(:,1)==d(1,1)) & d(1,1)~=1) 0053 for i=1:length(names) 0054 d=getfield(s,char(names(i))); 0055 d=d(x,:); 0056 s=setfield(s,char(names(i)),d); 0057 end 0058 else 0059 if(all(d(:,2)==d(1,2)) & d(1,2)~=1) 0060 for i=1:length(names) 0061 d=getfield(s,char(names(i))); 0062 d=d(:,x); 0063 s=setfield(s,char(names(i)),d); 0064 end 0065 else 0066 error('Dont know which array dim to cut over'); 0067 end 0068 end