function doesn't work in iteration

1 view (last 30 days)
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 Comment
Geoff Hayes
Geoff Hayes on 25 Jan 2015
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?

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 25 Jan 2015
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 Comments
fatema saba
fatema saba on 25 Jan 2015
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 on 25 Jan 2015
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).

Sign in to comment.

More Answers (0)

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!