Increase nonzero values without deleting zeros
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
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
2017-4-12
Ah true, the OP stated to increase it... but it's the same idea anyway. Just replace the * by a +.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!