필터 지우기
필터 지우기

Spit an array when the value 0 occurs until the value 2

조회 수: 2 (최근 30일)
Fabio Taccaliti
Fabio Taccaliti 2022년 6월 29일
댓글: Walter Roberson 2022년 6월 30일
I have an array time (6700x1) containing all numbers from -8 to 5 in ascending order.
I would like to have a new array (time_new) based on this that contains all value between 0 and 2.
I know that I can just open the array and look at which position the value 0 occurs and at wich index the value 2 and based on this do time(3981:4962). But since I'm dealing with several arrays where the position of these 2 numbers is not always the same I would like to have something more roboust that I can always use without every time open the array and look for the teo index.
Can someone help to with that?
Thanks in advance
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2022년 6월 29일
편집: Dyuman Joshi 2022년 6월 29일
Why do you think finding the position and using the index is not a robust method?
Use logical indexing then. (as @Voss has answered)

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

채택된 답변

Voss
Voss 2022년 6월 29일
% an array time (6700x1) containing numbers from
% -8 to 5 in ascending order:
time = linspace(-8,5,6700).'
time = 6700×1
-8.0000 -7.9981 -7.9961 -7.9942 -7.9922 -7.9903 -7.9884 -7.9864 -7.9845 -7.9825
% time_new based on this that contains
% all value between 0 and 2:
time_new = time(time >= 0 & time <= 2) % use >, < if you want to exclude 0, 2
time_new = 1031×1
0.0010 0.0030 0.0049 0.0069 0.0088 0.0107 0.0127 0.0146 0.0166 0.0185
  댓글 수: 4
Fabio Taccaliti
Fabio Taccaliti 2022년 6월 30일
Exactly, thanks a lot!
Voss
Voss 2022년 6월 30일
You're welcome!

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2022년 6월 29일
Your request is a bit ambiguous, so I will give two possibilities.
loc0 = find(YourArray == 0, 'first');
%use this
loc2F = find(YourArray == 2, 'first');
subsetF = YourArray(loc0:loc2F-1);
%OR use this
loc2L = find(YourArray == 2, 'last');
subsetL = YourArray(loc0:loc2L);
Now subsetF includes from the first 0 to the last value before the 2. subsetL includes from the first 0 to the last 2. You do not need both of these; I am just not clear which one you want.
Note that this code is not designed to work if there are no 0 or there are no 2.
  댓글 수: 3
Fabio Taccaliti
Fabio Taccaliti 2022년 6월 30일
Thanks for the answer.
I have this error.
Error using find
Second argument must be a positive scalar integer.
Walter Roberson
Walter Roberson 2022년 6월 30일
loc0 = find(YourArray == 0, 1, 'first');
%use this
loc2F = find(YourArray == 2, 1, 'first');
subsetF = YourArray(loc0:loc2F-1);
%OR use this
loc2L = find(YourArray == 2, 1, 'last');
subsetL = YourArray(loc0:loc2L);

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

카테고리

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

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by