How to change values between two values in an array
조회 수: 13 (최근 30일)
이전 댓글 표시
I need to replace certain values within an array that fall between 2 and 4. The code should find where the array equals 2 and then find the following location where the array equals 4 and replace all values with 3. Then it should find where the array equals 4 and then find the following location where the array equals 2 and replaces all of those values with 1. And then loop through the array until all values are 1, 2, 3 or 4 and in order (repeats of values are OK).
Here is an example array:
transitions = [1285738, 2, 2, 2915260, 4, 4290129, 2, 5650291, 4, 8030363, 2, 9337983, 4, 12040647];
I need to:
- change the values that fall between 2 and 4 to 3 (e.g., the 4th, 8th and 12th values should be 3)
- change the values between 4 and 2 to 1 (e.g., the 6th and 10th values should be 1)
댓글 수: 5
the cyclist
2021년 10월 4일
- If a 4 follows a 2, change every intervening value to 3, THEN
- If a 2 follows a 4, change every intervening value to 1
답변 (1개)
Swatantra Mahato
2021년 10월 7일
Hi Jake,
I am assuming you want to replace values in the array that occur between a 2 and 4, and those that occur between a 4 and 2.
One way of doing this I can think of is using the "find" function to get the indices of all the 2s and 4s as demonstrated below
transitions = [1285738, 2, 2, 2915260, 4, 4290129, 2, 5650291, 4, 8030363, 2, 9337983, 4, 12040647];
t=find(transitions==2)
f=find(transitions==4)
you can then loop over 'f' and 't' and replace the values in between accordingly
you can find more information and how-to examples on the "find" function in the documentation
Hope this helps
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!