Duplicate elements in each row

조회 수: 2 (최근 30일)
Isabella Kirksey
Isabella Kirksey 2022년 9월 25일
편집: dpb 2022년 9월 25일
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?

답변 (1개)

dpb
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...

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by