Problem in function

3 vues (au cours des 30 derniers jours)
Amir Hamzah UTeM
Amir Hamzah UTeM le 5 Mai 2011
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

Réponses (1)

Andrei Bobrov
Andrei Bobrov le 5 Mai 2011
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 commentaires
Amir Hamzah UTeM
Amir Hamzah UTeM le 5 Mai 2011
why it only valid for 7x7?
how to do for Nx7?
Andrei Bobrov
Andrei Bobrov le 5 Mai 2011
corrected in expression penalty=zeros(size(x,1),1);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by