Determine if an element in array of doubles start with patten

조회 수: 2 (최근 30일)
Mohamed Asaad
Mohamed Asaad 2023년 2월 12일
댓글: Adam Danz 2023년 2월 12일
Hey,
I need to find the index of the first element that starts with a specific number. So in this picture for example, if i give 8 as an input, i want the code to give me back the index of the first 8. that it meets which would be 163 in this case.

채택된 답변

Voss
Voss 2023년 2월 12일
idx = find(floor(data)==val,1)
where data is your array and val is what you're looking for, e.g., 8.
  댓글 수: 1
Adam Danz
Adam Danz 2023년 2월 12일
Neither of our current answers work with negative values although that may not be a problem in the OP's use case.
The benefit of this answer over mine is that val can be any number of digits. You could search for "82" in an array of values. It would match the third element of [8.2 820 82 8200].
The benefit of my answer over this one is that only the first digit is considered in the search but is limited to single-digit target values (which could easily by adapted). You could search for the number 8 in this vector and it would match the 3rd element. [0.8, 18, 8203, 8, 80].

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

추가 답변 (1개)

Adam Danz
Adam Danz 2023년 2월 12일
편집: Adam Danz 2023년 2월 12일
Here's a demo that finds the first value in a vector that has a first digit equal to 4. The values can have any number of digits to the left of the decimal although this doesn't work with negative values.
rng default
val = sort(rand(1,10).*randi(500,1,10))'
val = 10×1
6.9254 58.7631 60.8267 64.3632 221.9503 250.4717 253.5761 380.1302 440.2149 463.1465
target = 4;
firstDigit = cellfun(@(v)v(1),""+val)-'0'
firstDigit = 10×1
6 5 6 6 2 2 2 3 4 4
firstDigitIdx = find(firstDigit == target,1,'first')
firstDigitIdx = 9

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by