Deleting Elements in a Structure - Error Matrix Index is Out of Range
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a struct with several fields
x.score = [98 75 22 75 29];
x.count = [1 2 3 4 5];
I want to delete all the elements in x (in all fields) that have a count < 4. So in this case I want X to be
x.score = [98 75 22]
x.count = [1 2 3]
Why doesn't this cmd work?
x([x.count<4]) = []
댓글 수: 1
Stephen23
2022년 8월 20일
편집: Stephen23
2022년 8월 20일
"Why doesn't this cmd work?"
Because you are mixing up indexing into x (which is a scalar structure) with indexing into the fields of x (which are numeric vectors). If you want to remove elements from the fields of x then you need to index into those fields, and not by attempting to into the scalar structure x. Sometimes it is useful to index into a structure, but not if your goal is to index into its fields!
x.score = [98,75,22,75,29];
x.count = [1,2,3,4,5];
idx = x.count>=4;
x.score(idx) = [];
x.count(idx) = []
Note that these square brackets are completely superfluous, get rid of them: [x.count<4] Even if x was non-scalar that would still be invalid syntax, so they indicate (as most situations where a user has superfluous square brackets) a confusion about what square brackets do and when to use them:
y(1).count = 1;
y(2).count = 2;
[y.count<4] % square brackets don't do anything useful here either
채택된 답변
Voss
2022년 8월 19일
편집: Voss
2022년 8월 22일
x.score = [98 75 22 75 29];
x.count = [1 2 3 4 5];
x.count<4 is a 1x5 logical array
x.count<4
x(x.count<4) = [] would try to delete elements 1, 2, 3 of x (where x.count<4 is true), but you can't do that because x only has one element
size(x)
so you get the error.
Instead of deleting elements of x, you want to delete elements of each field of x, which can be done as follows:
f = fieldnames(x);
idx_to_delete = x.count<4;
for ii = 1:numel(f)
x.(f{ii})(idx_to_delete) = [];
end
disp(x)
This gives a result different than what you specified the result should be. Perhaps the condition should be x.count>=4?
x.score = [98 75 22 75 29]; % re-create x
x.count = [1 2 3 4 5];
f = fieldnames(x);
idx_to_delete = x.count>=4;
for ii = 1:numel(f)
x.(f{ii})(idx_to_delete) = [];
end
disp(x)
댓글 수: 4
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!