Replacing the zero entry of a vector with the corresponding entry of another vector of the same dimension.
1 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
Please I need some help about this:
Suppose I have 2 vectors A=[0;2;0] and B=[3;5;7]. How can I write a command in MATLAB that simply replace the zero entries of vector A with the corresponding non-zero entries of vector B?
In general, if I have 2 vectors A and B of the same dimension, assuming vector A have some zero entries, but the vector B have no zero entries. How can I replace the all the zero entries of vector A with that of the corresponding entries of vector B?
Thanks for any help.
0 个评论
采纳的回答
Birdman
2018-2-18
A(A==0)=B(A==0)
3 个评论
Birdman
2018-2-18
A==0
This is logical indexing. It returns 1 for the elements that are zero, and 0 for the elements that are not. By the power of MATLAB, we can easily use this boolean output to obtain indexes for the zero elements of a in B vector as follows:
B(A==0)
This is equivalent to
idx=find(A==0);
A(idx)=B(idx);
but my initial answer is more efficient and faster.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!