How to replace certain values in an array without using for-loop?
显示 更早的评论
I have a very long array of length couple million. Say, A=[1;2;3;4;5;2;3;4;1;....] I have another array of different length (order of thousands to millions), we can call this second array B.
I would like to replace values in the first array with 0s if the value in A is present in B.
Currently, I have the following code to do it:
for i=1:length(B)
A(A==B(i))=0;
end
However, I would like to get rid of for loop and make this as efficient as possible since the arrays that I am working with is very large, and this is only a very small portion of the entire code, which needs to be computable before I graduate.
Thank you in advance,
回答(1 个)
Azzi Abdelmalek
2013-7-16
编辑:Azzi Abdelmalek
2013-7-16
A(ismember(A,B))=0
4 个评论
Louis
2013-7-16
Azzi Abdelmalek
2013-7-16
Look at this test
A=randi(1000,1000);
B=randi(1000,1000,1);
A1=A;
B1=B;
tic
for i=1:numel(B)
A(A==B(i))=0;
end
time_with_loop=toc
%-------------------------------
tic
A1(ismember(A1,B1))=0;
time_with_ismember=toc
time_with_loop = 2.3960
time_with_ismember =0.0900
Muthu Annamalai
2013-7-16
@Azzi shouldn't logical indexing work in this case?
A1( A1 == B1 ) = 0
Image Analyst
2013-7-16
No, it won't. That will work only if they match up. It won't remove elements that occur anywhere in A or B.
类别
在 帮助中心 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!