# Increase nonzero values without deleting zeros

11 Ansichten (letzte 30 Tage)
monmatlab am 12 Apr. 2017
Kommentiert: David J. Mack am 12 Apr. 2017
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 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
monmatlab am 12 Apr. 2017
Bearbeitet: monmatlab am 12 Apr. 2017
at their initial positions. I want to have the same vector , just with the nonzeros increased by ten

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

David J. Mack am 12 Apr. 2017
Bearbeitet: David J. Mack am 12 Apr. 2017
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 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
David J. Mack am 12 Apr. 2017
Ah true, the OP stated to increase it... but it's the same idea anyway. Just replace the * by a +.

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

X = ( X ~= 0 ) .* ( X + 10 );
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!