Problem in function

1 次查看(过去 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 CenterFile Exchange 中查找有关 Whos 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by