function doesn't work in iteration
1 次查看(过去 30 天)
显示 更早的评论
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
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
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 个评论
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!