Remove structs from an array of structs

조회 수: 10 (최근 30일)
Bartolomeo Ruotolo
Bartolomeo Ruotolo 2016년 2월 5일
편집: Guillaume 2016년 2월 5일
I have a 1x1 struct A with 13 fields. One of these field, B, is a 15x1 cell, each cell is a 1x1 struct with 5 fields. How can I remove some of these structures contained in the cell with particular value in the field called 'name'? I've tried in this way:
for k = 1 : length(A.B) if A.B{k,1}.name = 'relax' A.B{k,1} = [] end end
The error is:
Error: File: xxx.m Line: 5 Column: 45 The expression to the left of the equals sign is not a valid target for an assignment.

채택된 답변

Guillaume
Guillaume 2016년 2월 5일
= is for assignment, == is for comparison. However, == does not work with strings, you use strcmp for that:
for cellidx = 1 : numel(A.B) %numel is a lot safer than length
if strcmp(A.B{cellidx}.name, 'relax')
A.B{cellidx} = [];
end
end
  댓글 수: 2
Bartolomeo Ruotolo
Bartolomeo Ruotolo 2016년 2월 5일
Thank you very much, Sir. Now to remove the empty rows, can I use reshape?
Guillaume
Guillaume 2016년 2월 5일
편집: Guillaume 2016년 2월 5일
reshape will never remove any element. If you wanted to get rid of the cells of B instead of filling them with empty, this is what you should have done:
for cellidx = 1 : numel(A.B) %numel is a lot safer than length
if strcmp(A.B{cellidx}.name, 'relax')
A.B(cellidx) = []; %note the use of () instead of {}
end
end
{} refers to the content of a cell, therefore when you do B{x} = []; you put empty in cell x.
() referes to the cell itself, therefore when you do B(x) = []; you remove the cell x itself.
If you've already set the cells content to empty, to delete those cells you'd do:
A.B(cellfun(@isempty, A.B)) = [];

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by