Increase nonzero values without deleting zeros

조회 수: 9 (최근 30일)
monmatlab
monmatlab 2017년 4월 12일
댓글: David J. Mack 2017년 4월 12일
I have a vector X.
X=[0 0 0 0 1 1 1 1 0 0 0 0 0 0 2 2 2 2 2 2 0 0 0 3 3 3 3 0 0 0 0 0 4 4 4]
I want to increase the values of the nonzero elements in vector X by 10 However, when I do this using the find function I end up just having a vector without the zeros.
Y=X((find(X~=0)))+10;
Y=[11 11 11 11 22 22 ... ]
Is there a way to do this without using a for loop?
  댓글 수: 2
KSSV
KSSV 2017년 4월 12일
Where you want to place the non zeros numbers?
monmatlab
monmatlab 2017년 4월 12일
편집: monmatlab 2017년 4월 12일
at their initial positions. I want to have the same vector , just with the nonzeros increased by ten

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

채택된 답변

David J. Mack
David J. Mack 2017년 4월 12일
편집: David J. Mack 2017년 4월 12일
Hey monmatlab, simply use logical indexing:
Y = X;
isNonzero = X~=0;
Y(isNonzero) = 10*Y(isNonzero);
or the more compact inplace replacement:
X(X~=0) = 10*X(X~=0);
Greetings, David
  댓글 수: 2
Adam
Adam 2017년 4월 12일
If this is what you actually want to do, with multiplication then you can just skip the logical part and use
X = X * 10
since multiplying by 0 is 0 anyway! I was under the impression you wanted to add 10, not multiply by it though.
David J. Mack
David J. Mack 2017년 4월 12일
Ah true, the OP stated to increase it... but it's the same idea anyway. Just replace the * by a +.

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

추가 답변 (1개)

Adam
Adam 2017년 4월 12일
X = ( X ~= 0 ) .* ( X + 10 );

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by