-1

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.

Shai
  • 111,146
  • 38
  • 238
  • 371
Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • Are you treating `C.Ck` as a matrix or a vector? what should happen to its shape once you discard elements larger than 10? Did you by any chance meant to se `numel` instead of `length`? – Shai Feb 17 '13 at 15:06
  • BTW, next time, try editing your questions instead of delete and re-post... – Shai Feb 17 '13 at 15:06

1 Answers1

2

To remove an element from an array you can simply assign it to an empty array ([]):

C.Ck(ii) = []; % removed the ii-th element of C.Ck.

A few comments:

  1. Use dynamic field names only when you need them to be dynamic. If the field name is always Ck it is much better to access it as C.Ck than C.(sprintf('Ck')).

  2. Try not to use i and j as variable names in matlab.

  3. If you are using ii as an index to C.Ck inside a for loop it is a bit risky to change the size of C.Ck inside the loop. (See e.g., this question).

  4. If you just want to discard elements of C.Ck that are larger than 10, all you need is

    C.Ck( C.Ck > 10 ) = [];
    

    or

    cleared = C.Ck( C.Ck <= 10 );
    
Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Is there a way to remove a **specific** element? For example, only `67`? Is there a way to do that? I think this would work: ` C.Ck(C.Ck == 67) = []`? Thanks – Simplicity Feb 17 '13 at 15:35
  • @Med-SWEng - you are correct. But would happen to the shape of your matrix if you remove a single element? Try that in Matlab and see what happens... – Shai Feb 17 '13 at 15:39