How do I add values to specific values/ specific place of an already existing array?

조회 수: 2 (최근 30일)
Goncalo Costa
Goncalo Costa 2021년 10월 13일
편집: C B 2021년 10월 15일
I have an array of number, t , from which I have extracted some elements at even intervals (every 30 elements, one was extracted) into an array, A.
I now intend to select specific elements in A that meet a condition (if statement), and add x elements to it (x/2 to each side). These new elements to be added are the ones around those specific elements in t (x/2 in each side).
e.g. t = [1.5, 2.5 ,3.5, 4.5, 5.5 ,6.5, 7.5, 8.5, 9.5, 10.5] ;
A = [3.5, 5.5, 7.5],
and in this case I will choose x = 2 elements.
I want to add 2 elements from t to A and finish with A = [ 2.5 ,3.5, 4.5, 5.5 , 6.5, 7.5, 8.5 ]

답변 (1개)

C B
C B 2021년 10월 13일
편집: C B 2021년 10월 15일
@Goncalo Costa will this work for you?
t = [1.5, 2.5 ,3.5, 4.5, 5.5 ,6.5, 7.5, 8.5, 9.5, 10.5]
t = 1×10
1.5000 2.5000 3.5000 4.5000 5.5000 6.5000 7.5000 8.5000 9.5000 10.5000
A = [3.5, 5.5, 7.5]
A = 1×3
3.5000 5.5000 7.5000
x = 2
x = 2
reqx =x/2;
Index = arrayfun(@(x) findstr(x,t),A)
Index = 1×3
3 5 7
finalIndex =[];
for i=1:length(Index)
finalIndex = [finalIndex Index(i)-reqx:Index(i)+reqx]
end
finalIndex = 1×3
2 3 4
finalIndex = 1×6
2 3 4 4 5 6
finalIndex = 1×9
2 3 4 4 5 6 6 7 8
finalIndexUnique = unique(finalIndex)
finalIndexUnique = 1×7
2 3 4 5 6 7 8
requiredAnswer = t(finalIndexUnique)
requiredAnswer = 1×7
2.5000 3.5000 4.5000 5.5000 6.5000 7.5000 8.5000
  댓글 수: 1
C B
C B 2021년 10월 13일
@Walter Roberson Any better way i can handle below line as it changes size on every loop.
finalIndex = [finalIndex Index(i)-reqx:Index(i)+reqx]

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by