Using matlab to evolute a simple vector , but not fit the inference

1 vue (au cours des 30 derniers jours)
Darcy Chou
Darcy Chou le 27 Fév 2019
Commenté : Darcy Chou le 3 Mar 2019
clear
clc
time = 4;
size = 8;
% initialize.
a = ones(time,size);
a(1,6) = 5;
% if a(i)>1,then a(i)=a(i)-1 and a(i-1)=a(i-1)+1.
% Saved in a new row.
for t = 1:time-1
for i = 2:size
if a(t,i)>1
a(t+1,i-1) = a(t,i-1) + 1;
a(t+1,i) = a(t,i) - 1;
end
end
end
ans = a(:,:)
Notice the code above, and I want to achieve :
1 1 1 1 1 5 1 1
1 1 1 1 2 4 1 1
1 1 1 2 2 3 1 1
1 1 2 2 2 2 1 1
but the answer is:
1 1 1 1 1 5 1 1
1 1 1 1 2 4 1 1
1 1 1 2 3 3 1 1
1 1 2 3 4 2 1 1
Where is wrong?
  1 commentaire
Jos (10584)
Jos (10584) le 28 Fév 2019
A tip: do not use names for variables that are also functions, like size ;-)

Connectez-vous pour commenter.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 28 Fév 2019
Modifié(e) : Andrei Bobrov le 28 Fév 2019
m = 4;
n = 8;
a = ones(m,n);
a(1,6) = 5;
for ii = 1:m-1
for jj = 2:n
if a(ii,jj)>1
if ii == 1
I = jj;
a(ii+1,jj-1) = a(ii,jj-1) + 1;
a(ii+1,jj) = a(ii,jj) - 1;
break
end
a(ii+1,jj-1:I-1) = a(ii,jj);
a(ii+1,I) = a(ii,I) - 1;
break
end
end
end
or
m = 4;
n = 8;
a = ones(m,n);
a(1,6) = 5;
[I,J] = find(a>1);
a(:,J - m:J - 1) = a(:,J - m:J - 1) + flip(tril(ones(m),-1),2);
a(:,J) = a(I,J) - (0:m-1)';

Plus de réponses (1)

David Goodmanson
David Goodmanson le 28 Fév 2019
Modifié(e) : David Goodmanson le 28 Fév 2019
Hi Darcy,
It appears that the rule you want is
a(t+1,i-1) = a(t+1,i-1) + 1
which does give the result you are looking for. For a(t+1,i-1) This allows the lowering effect due to a(t,i-1)>1 to persist until it is raised by by the effect due to a(t,1)>1.
  1 commentaire
Darcy Chou
Darcy Chou le 3 Mar 2019
Thank you . Codes submited by Andrei Bobrov are right.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Tags

Produits


Version

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by