Problem in function

3 ビュー (過去 30 日間)
Amir Hamzah UTeM
Amir Hamzah UTeM 2011 年 5 月 5 日
i create a function to calculate the penalty for certain data,it only valid for data is 1xN. when i try to do for data MxN,the process take too long until my matlab crash.how to solve this problem?
not problem when: x=[33,22,33,33,33,11] (1xN)
got problem when: x=[33,22,33,33,33,11,22;
33,11,33,22,33,33,11] (MxN)
here my code..
function [penalty] = calcpenalty(x)
r3penalty=0;
r2penalty=0;
r1penalty=0;
penalty=0;
for ii = 1:size(x,1)
c = 1;
Y = x(ii,:)==33;
while c <= length(x)-2
if Y(c)
if Y(c+1:c+2) % Three in a row.
r3penalty=1
c = c + 4;
elseif Y(c+1)==33 % Two in a row.
r2penalty=1
c = c + 3;
elseif x(c+1)==11 % Just one 33.
r1penalty=1
c = c + 2;
elseif x(c+1)==22
c = c + 1;
else
end
else
c = c + 1;
end
end
end
penalty(:,1)=r1penalty+r3penalty+r2penalty

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2011 年 5 月 5 日
so?
function [penalty] = calcpenalty(x)
r3penalty=0;
r2penalty=0;
r1penalty=0;
penalty=zeros(size(x,1),1);
for ii = 1:size(x,1)
c = 1;
Y = x(ii,:)==33;
while c <= length(x)-2
if Y(c)
if Y(c+1:c+2) % Three in a row.
r3penalty=1;
c = c + 4;
elseif x(ii,c+1)==33 % Two in a row.
r2penalty=1;
c = c + 3;
elseif x(ii,c+1)==11 % Just one 33.
r1penalty=1;
c = c + 2;
elseif x(ii,c+1)==22
c = c + 1;
end
else
c = c + 1;
end
end
penalty(ii,1)=r1penalty+r3penalty+r2penalty;
end
the same thing, is not it?
penalty = sum([true(size(x,1),1) diff(Y,[],2)~=0]&Y,2);
  2 件のコメント
Amir Hamzah UTeM
Amir Hamzah UTeM 2011 年 5 月 5 日
why it only valid for 7x7?
how to do for Nx7?
Andrei Bobrov
Andrei Bobrov 2011 年 5 月 5 日
corrected in expression penalty=zeros(size(x,1),1);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by