I have the following code in matlab and trying to remove an element from a struct:
function test()
C = struct;
C.(sprintf('Ck')) = [1 6 8 9; 8 6 9 7; 7 6 67 6; 65 7 8 7];
ck_length = length(C.(sprintf('Ck')));
for i=1:ck_length
if C.(sprintf('Ck'))(i)> 10
cleared = rmfield(C.(sprintf('Ck')), C.(sprintf('Ck'))(i));
end
end
end
But, when I run the program I get an error as shown below:
>> test
??? Error using ==> rmfield at 19
S must be a structure array.
Error in ==> test at 89
cleared = rmfield(C.(sprintf('Ck')), C.(sprintf('Ck'))(i));
How can I solve this issue?
Thanks.
To remove an element from an array you can simply assign it to an empty array (
[]):A few comments:
Use dynamic field names only when you need them to be dynamic. If the field name is always
Ckit is much better to access it asC.CkthanC.(sprintf('Ck')).Try not to use
iandjas variable names in matlab.If you are using
iias an index toC.Ckinside aforloop it is a bit risky to change the size ofC.Ckinside the loop. (See e.g., this question).If you just want to discard elements of
C.Ckthat are larger than 10, all you need isor