Problem in function

조회 수: 9 (최근 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);

댓글을 달려면 로그인하십시오.

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by