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

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 Comment

A tip: do not use names for variables that are also functions, like size ;-)

Sign in to comment.

 Accepted Answer

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)';

More Answers (1)

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.

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2016b

Tags

Community Treasure Hunt

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

Start Hunting!