MATLAB: Help with removing arrays from structure array

MATLABstructure array remove array index

Hello. I have 1×50 structure array called 'data2' with 18 fields. I am trying to remove arrays that have zero matrices in their fields. Example is data2(1) as shown below.
data2(1)
ans=
type: 'A321'
time: [0x1 double]
lat: [0x1 double]
lng: [0x1 double]
altitude: [0x1 double]
selected_altititude: [0x1 double]
BPS: [0x1 double]
RA: [0x1 double]
TTA: [0x1 double]
GS: [0x1 double]
TAR: [0x1 double]
TAS: [0x1 double]
heading: [0x1 double]
IAS: [0x1 double]
Mach: [0x1 double]
BAR: [0x1 double]
IVV: [0x1 double]
wind: [0x1 double]
I am using the following code to try to remove the arrays.
for n = 1 : length(data2)
if isempty(data2(n).TTA)
data2(n) =[];
end
end
Can anyone explain me what is wrong? (I am using the field TTA solely because of my preference. I can use any of them, since all of them are either zeros, or have values.) Thanks.

Best Answer

When you write
for k=1:2
data(k)=[]
end
at the first iteration, the size of of data2 will be equal to 1. then, when k is equal to 2, you will get an error: Index exceeds matrix dimensions. You can do it without a for loop
data2=struct('field1' , {1 2 3 4 },'field2',{4 zeros(0,1) 40 zeros(0,1)}) % Example
a={data2.field2}
idx=cellfun(@isempty,a)
data2(idx)=[]