number of elements

I have an array A(1483 rows, 417 columns) with integer values of 1 to 5. I want to know whithin each block 92*92(i:i+91,j:j+91), what is the percentage of each value. I looked at size(), hist(), numel() but I don't think they can do what I want. Could you please help me?

 채택된 답변

Walter Roberson
Walter Roberson 2011년 4월 28일

1 개 추천

M = A(i:i+91,j:j+91);
h = histc(M(:), 1:5);
p = h ./ (92*92) * 100;

댓글 수: 1

Hassan
Hassan 2011년 4월 28일
thanks a lot Walter. your code works fine.
I wrote the following code but yours is more efficient, shorter and faster.
M = A(i:i+91,j:j+91);
n=numel(M)
n1=numel(find(M==1))
n2=numel(find(M==2))
n3=numel(find(M==3))
n4=numel(find(M==4))
n5=numel(find(M==5))
p1=n1*100/n
p2=n2*100/n
p3=n3*100/n
p4=n4*100/n
p5=n5*100/n

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2011년 4월 28일

0 개 추천

variant the full solutions
A = randi([1 5], 1483,417);
m = 92;
mn = fix(size(A)/m);
Awork = A(1:mn(1)*m,1:mn(2)*m);
A1 = reshape(permute(reshape(Awork,m,mn(1),m,[]),[1 3 2 4]),m^2,[]);
A2 = arrayfun(@(x)histc(A1(:,x),1:5),1:prod(mn),'UniformOutput' , false);
Out = cell2mat(A2)/m^2;
more variant
A = randi([1 5], 1483,417);
m = 92;
mn = fix(size(A)/m);
Awork = A(1:mn(1)*m,1:mn(2)*m);
A1 = reshape(permute(reshape(Awork,m,mn(1),m,[]),[1 3 2 4]),m^2,[]);
Out = cell2mat(arrayfun(@(x)histc(A1(:,x),1:5)/nnz(A1(:,x)),1:prod(mn),'UniformOutput' , false));

댓글 수: 6

Walter Roberson
Walter Roberson 2011년 4월 28일
Hmmm, yes -- what to do about the boundaries? 417 certainly isn't a multiple of 92. Andrei's code stays sane by using a temporary matrix that is multiples of 92 in each direction.
Hassan
Hassan 2011년 4월 29일
thanks Andrei for the comment. I used your code but I didn't get the same results as I got from Walter's.
I have some zero values in my data that want to be excleded while the percentage of values>0 are calculated. could you please help me?
Hassan
Hassan 2011년 4월 29일
in my code, I can use n=numel(find(M~=0)).
Andrei Bobrov
Andrei Bobrov 2011년 4월 29일
understood, working
Walter Roberson
Walter Roberson 2011년 4월 29일
In my code, if you have some 0 values that you need to be ignored when calculating percentages, then instead of using
p = h ./ (92*92) * 100;
you should use
p = h ./ sum(h) * 100;
Note though that this will give a vector of nan if all the elements in the block are zero.
Hassan
Hassan 2011년 4월 29일
thanks a lot Walter.

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

카테고리

도움말 센터File Exchange에서 Component-Based Modeling에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by