How to count repeated rows of characters using a loop?

조회 수: 6 (최근 30일)
Jason
Jason 2014년 3월 23일
댓글: Image Analyst 2014년 3월 23일
Say I have an array (I have already sorted alphabetically): results=[ABC;ABC;DEF;GHI;GHI;....]. I must use either a 'for' or 'while' loop (and I believe an 'if' statement will also make this easier) to find out how many times any repeated rows appear. i.e my above results would end up as [2;1;2;...]
thank you
  댓글 수: 3
Jan
Jan 2014년 3월 23일
"results=[ABC;ABC;DEF;GHI;GHI;...." is no valid Matlab syntax. Is this a cell string or a CHAR matrix? Some quote characters are missing in both cases.
Jason
Jason 2014년 3월 23일
I am GIVEN a CHAR matrix, all values already entered. To date all I have done is use "sortrows" to put the matrix in alphabetic order. My issue is coming to the loop, I have:
for 1:1:length(results)
if results(i,:)==results(i+1,:)
count= i+1
end
end
then matlab tells me "Index exceeds matrix dimensions"

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2014년 3월 23일
Hint: have you looked into sortrows() and unique()? If I were to do it for you, that's what I'd be looking up. Or maybe use hist(). Have you tried anything yet? Is this homework?
  댓글 수: 2
Jason
Jason 2014년 3월 23일
I've done sortrows() and tried playing around with unique(), but not hist(). I was able to make it work with:
[resultsx,resultsy]=unique(results,'rows');
n=accumarray(resultsy,1);
count = diff(resultsy)
But unfortunately I cannot use this since it is homework and we are specifically told to use a loop.
Image Analyst
Image Analyst 2014년 3월 23일
Jason, you should have tagged it as homework. Please do so now. OK, so you have a loop over rows - that should be obvious, right. Now what? How about having another loop inside over rows from 1 to the current row where you check the current row against all 3 column elements of all prior rows ? That seems to make sense. Now if a match is found, you'll need to increment something, and if no match is found, it's the first one found so far so you need to set the count array to 1 for that pattern. Just think it through and you'll get it. Come back with more code if you have trouble. We can't just hand over to you a turnkey solution.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by