How to Change element values of an array with conditions?

조회 수: 77 (최근 30일)
satheeshkumar satheeshkumar M
satheeshkumar satheeshkumar M 2017년 10월 31일
댓글: Fangjun Jiang 2019년 11월 11일
If suppose, A=[2 3 4 7 9 10] i want to use if condition to add (e.g) 10 to the elements less than 6 (< 6) of array A, so that my array should convert into A=[12 13 14 7 9 10]. how can i achieve?

채택된 답변

Adam
Adam 2017년 10월 31일
편집: Adam 2017년 10월 31일
A( A < 6 ) = A ( A < 6 ) + 10
Sadly Matlab doesn't have a neat += operator so you have to do the above rather ugly equivalent, though I would often pull the logical indexing out into its own variable.
  댓글 수: 3
Erik Elander Aman
Erik Elander Aman 2019년 11월 10일
Is there a similar solution for when you would like to alter in an interval within two limits, eg. adding 10 to each value between 4 and 6 in the array?
Fangjun Jiang
Fangjun Jiang 2019년 11월 11일
index=and(A>4,A<6);
A(index)=A(index)+10;

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

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2017년 10월 31일
Play golf?
A=A+10*(A<6)
  댓글 수: 2
satheeshkumar satheeshkumar M
satheeshkumar satheeshkumar M 2017년 11월 1일
smartly working, thanks
Eliot Bethke
Eliot Bethke 2019년 3월 20일
I prefer this answer because you can assign the result of the operation to a different variable. Also works if you wanted to multiply instead of add:
S = A .* 10 .* (A < 6);

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

카테고리

Help CenterFile Exchange에서 Simulink Environment Customization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by