Reputation: 111
I'm struggling to write this question into Matlab Code. I know that I should use a 'for' loop, but I don't know how to use this to do it. Consider the following sequence of row vectors v(n) for n ≥ 1:
v(1) = (1)
v(2) = (1, 1)
v(3) = (2, 1)
v(4) = (1, 2, 1, 1)
v(5) = (1, 1, 1, 2, 2, 1)
v(6) = (3, 1, 2, 2, 1, 1)
Each row is given by reading out the contents of the row above, so for example v(6) contains “three ones, two twos, one one” and this gives v6. Write a script to print v(n) for n = 1 up to n = 12.
Upvotes: 0
Views: 132
Reputation: 2983
One possible version:
N = 6;
v = cell(N,1);
v{1} = 1;
for ii = 2:N
v1 = v{ii-1};
stop_point = find(diff(v1));
if isempty(stop_point)
n = length(v1);
m = v1(1);
v{ii} = [n,m];
else
n = diff([0,stop_point,length(v1)]);
m = v1([stop_point,end]);
v2 = [n;m];
v{ii} = v2(:).';
end
end
Example output:
>> v{:}
ans =
1
ans =
1 1
ans =
2 1
ans =
1 2 1 1
ans =
1 1 1 2 2 1
ans =
3 1 2 2 1 1
>>
Note: Row vectors of unequal lengths cannot be contained in a matrix. An easy way to store them is using a cell array.
Upvotes: 1