Simple For Loop To Find Indices

조회 수: 1 (최근 30일)
Melissa
Melissa 2015년 4월 20일
편집: Guillaume 2015년 4월 20일
Hello.
I have a question about a simple for loop. I have an original latlon set of about 500x1 unique coordinates. I have a subset of that latlon set in which I would like to find the indices for. So I have created a for loop to try to find it.
indices = zeros(length(subset),1); %create matrix of zeros to fill
for ii=1:length(subset);
indices(ii) = find(original==subset(ii));
end
But I keep getting: Subscripted assignment dimension mismatch. What am I doing wrong? In the end I want a matrix the size of the subset to indicate which indices are correlated to my latlon subset in relation to my original latlon.
Thank you,
Melissa

채택된 답변

Guillaume
Guillaume 2015년 4월 20일
편집: Guillaume 2015년 4월 20일
The only way you can get this error with the code you've presented is if is find returns strictly less or more than one element, that is either the element of your subset is not found, or it is found more than once (i.e. your original array is not unique).
In any case, the loop is not needed there are set functions already present in matlab to do what you want. In your case, it's simply:
[~, indices] = ismember(subset, original)

추가 답변 (1개)

Hikaru
Hikaru 2015년 4월 20일
편집: Hikaru 2015년 4월 20일
Are your variables stored as double, or cells?
edit: I'm sorry. I made a mistake and I removed the incorrect statement.
  댓글 수: 2
Melissa
Melissa 2015년 4월 20일
Hi Hikaru,
They're stored as double. So how should I modify it so that I am not comparing a whole vector to one value? Do I add another loop inside of that loop?
Hikaru
Hikaru 2015년 4월 20일
I tried your code using a smaller sized variables,
original = [60; 40; 100; 120];
subset = [120; 40; 60];
indices = zeros(length(subset),1);
for ii=1:length(subset);
indices(ii) = find(original==subset(ii))
end
and it works okay as long as the values in subset can also be found in the original vector.
I'm not sure why you got that error without looking at the sample matrix, but have you check if there are same values in the original vector?

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by