Duplicate elements in each row
7 次查看(过去 30 天)
显示 更早的评论
I have the following code to find duplicate elements in each row of a matrix:
for i=1:length
counts=hist(same(i,1:5),13);
a=ismember(3,counts);
b=ismember(2,counts);
c(i)=a+b;
trip(i)=sum(counts==3);
end
The code works but starts to run into runtime issues with big matrix sizes. Is there a way I can do this without using a for loop?
0 个评论
回答(1 个)
dpb
2022-9-25
编辑:dpb
2022-9-25
Sure, if am reading the desired output correctly -- NB it appears your c variable is indexed incorrectly; it should be a logical array the size of the input array (or it's missing "the curlies" {} to make it a cell array by row).
I'll use "A" here for brevity for the input array...
c=(A==2)|(A==3); % logical array of locations == 2 or 3, address eadh row as c(i,:)
trip=sum(A==3,2); % number == 3 only by row
I'm guessing doing the comparison twice is going to be as fast (or nearly so) as the route of saving the temporary to build the logical array such as
a=(A==2);
b=(A==3);
c=a|b;
trip=sum(b,2);
but you can test both...
0 个评论
另请参阅
类别
在 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!