remove the row of a structure where the number 2 is standing in matlab

Suppose myStruct is the structure, and numToRemove is the number that is to be removed, we can use logical indexing to remove the row that contains a particular value in a structure.

main.m
myStruct([myStruct.fieldName] == numToRemove) = [];
52 chars
2 lines

Here, we use the [myStruct.fieldName] == numToRemove to identify the rows that contain the number we want to remove and then assign the remaining structure to the original variable.

Note: fieldName is the name of the field that contains the number.

Alternatively, we can use a for loop to look for the row with the number we want removed and assign the remaining values to a new temporary structure.

main.m
tempStruct = struct();
j = 1;
for i = 1:length(myStruct)
    if myStruct(i).fieldName ~= numToRemove
        tempStruct(j) = myStruct(i);
        j = j + 1;
    end
end
myStruct = tempStruct;
192 chars
10 lines

The above code creates an empty temporary structure, tempStruct, and loop through each row of myStruct. If the row contains a value other than numToRemove, then it is added to tempStruct. Finally, the new structure is assigned to the original variable.

Note: fieldName is the name of the field that contains the number.

gistlibby LogSnag