Location of value in cell array

I have a 2 element cell array:
cell={x y}
x & y are both the same length. I am trying to compare each value in y against a set of user defined inputs, and delete it and its corresponding x if it is outside the range.
lowerbound=str2double(get(handles.min,'String'));
upperbound=str2double(get(handles.max,'String'));
for i=1:length(cell{2})
if cell{2}(i)<lowerbound || cell{2}(i)>upperbound
cell{1}(i)=[];
cell{2}(i)=[];
end
end
However I'm getting Index exceeds matrix dimensions error in the 4th line. I don't see why, but I assume I am misunderstanding on how to address each individal value.

 채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 11월 4일

0 개 추천

When you delete some of the elements using cell{1}(i)=[], the length of cell{1} reduces thus cause "Index exceeds matrix dimensions error" when i reaches the end.
Use logic index instead and no need to do the for-loop.
index=cell{2}<lowerbound | cell{2}>upperbound;
cell{1}(index)=[];
cell{2}(index)=[];

댓글 수: 5

Jared
Jared 2011년 11월 4일
The first part makes clear sense to me but I'm having a hard time wrapping my head around the index= line. Wouldn't index always be 0 or 1?
Fangjun Jiang
Fangjun Jiang 2011년 11월 4일
Yes. See A=[1 2 3]; index=logical([1 0 1]); A(index)
You can sense that if the index value is true, the corresponding element is selected. If the index value is false, the corresponding element is not selected.
Walter Roberson
Walter Roberson 2011년 11월 4일
And note, Jared, that for this to work, the values must be of datatype logical (true or false). If you were to remove the logical() part from Fangjun's example, you would get an error message about the indexes needing to be logical or positive integers.
Jan
Jan 2011년 11월 4일
The || operator needs scalar inputs. I'd prefer "or()" here.
Fangjun Jiang
Fangjun Jiang 2011년 11월 4일
@Jan, you are right. My answer is updated.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2011년 11월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by