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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by