function doesn't work in iteration

조회 수: 1 (최근 30일)
fatema saba
fatema saba 2015년 1월 25일
댓글: Geoff Hayes 2015년 1월 25일
Hello I have a question please. I have a 3D matrix named "x"
x(:,:,1)=[0 0 1 0 0;0 0 0 0 0;0 1 0 0 0;0 0 0 0 1]
x(:,:,2)=[1 1 1 1 1;0 1 1 1 1;1 0 1 1 1;1 1 1 1 1]
I write a function that calculates level of compactness for elements with value 1 in this matrix.
I have to calculate amount of "comp" for every dimension and then add them together.
but my script doesn't work correctly. Is it possible to guide me please.
i
function comp=mycompact(x)
[m n k]=size(x)
%calculate perimeter
cells=m*n
for K=1:k
cellsone_x(K)=nnz(x(:,:,K))
case1_matches(:,:,K) = x(1:end-1,:,K) == x(2:end,:,K) & x(1:end-1,:,K)==1
case2_matches(:,:,K) = x(:,1:end-1,K) == x(:,2:end,K) & x(:,1:end-1,K)==1
pc_x(K) = sum(case1_matches(:)) + sum(case2_matches(:))
perimeter(K)=4*cellsone_x(K)-2*pc_x(K)
minconfig(K)=(4*cellsone_x(k))
maxcomfig(K)=4*(sqrt(cellsone_x(K)))
comp(K)=(minconfig(K)-perimeter(K))/(minconfig(K)-maxcomfig(K))
end
comp=sum(comp(k))
Thank you
  댓글 수: 1
Geoff Hayes
Geoff Hayes 2015년 1월 25일
Fatema - please elaborate on what you mean by by my script doesn't work correctly. What exactly do you mean by this? Is there an error (and if so what is it) or are you observing incorrect values?

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

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 1월 25일
Fatema - when I run your code with the inputs that you have described, I observe the following error
Attempted to access cellsone_x(2); index out of bounds because
numel(cellsone_x)=1.
Error in mycompact (line 11)
minconfig(K)=(4*cellsone_x(k))
Note how you are using a lower case k to access cellsone_x when in every other line you are using an upper case K. Try replacing line 11 with
minconfig(K)=(4*cellsone_x(K));
which should allow the code to proceed without error.
  댓글 수: 2
fatema saba
fatema saba 2015년 1월 25일
Thank you for your tip.
I change it also I change the last line to:
i
comp=sum(comp)
end
It works.
Thank you.
Geoff Hayes
Geoff Hayes 2015년 1월 25일
Fatema - I'm not sure why you have included the i as it doesn't seem to serve any purpose (so you could remove it).

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by