How do I search through a tall array element by element?

조회 수: 6 (최근 30일)
littlepho
littlepho 2017년 4월 10일
댓글: James Tursa 2017년 4월 12일
I would like to be able to search through a tall array for a specific item. However, it seems any logical operator cannot be used with tall arrays. For example:
A = rand(1000,1);
tA = tall(A);
for i=1:1000
if tA(i) == 0.5
disp('i is equal to 0.5')
end
end
This code will result in a 'conversion to logical from tall is not possible' error. So is there a way to search through a tall array without using subsets of the array, such as:
tAsubset = gather(tA(1:100));

채택된 답변

Edric Ellis
Edric Ellis 2017년 4월 11일
You can make this code work by writing
if gather(tA(i) == 0.5)
disp('i is equal to 0.5')
end
however this will be incredibly inefficient - each call to gather needs to pass over the data. You can use the == operator on the whole array to get a tall logical result.
isHalf = (tA == 0.5);
Or, bearing in mind the sound advice from @Image Analyst, you could use a tolerance (unfortunately tall arrays don't support ismembertol)
isRoughlyHalf = (tA >= 0.49 & tA <= 0.51);
The real question is what do you want to do next with all the entries that satisfy the criterion? You could gather just those using logical indexing
dataSubset = tA(isRoughlyHalf);
gather(dataSubset);
or perform some other operation on the subset of data.
  댓글 수: 3
Edric Ellis
Edric Ellis 2017년 4월 12일
The ability to use some forms of numeric subscripts in the first dimension (including this form) was added in R2017a - but you're right, this wouldn't work in R2016b.
James Tursa
James Tursa 2017년 4월 12일
Yes, I was running R2016b ...

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

추가 답변 (2개)

Image Analyst
Image Analyst 2017년 4월 11일
You can't test floating point numbers for equality. See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
You can use ismembertol().

James Tursa
James Tursa 2017년 4월 11일
편집: Guillaume 2017년 4월 11일
tall arrays are not "in memory". As such, they cannot be used for controlling "if" and "while" statements since their values (and results of operations on their values) isn't known to the code until they are "gathered" into memory. So you cannot do what you are trying to do the way you are trying to do it. If you really want to use tall array elements this way, you will need to gather subsets into memory so that the results can be used in "if" tests and "while" loops. E.g., see this deferred evaluation link:
Also, you can't use arbitrary indexes with tall arrays, so there will be restrictions on how you can pull the subsets out. See the doc.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by