matlab - A table with 2 columns where one column increases sequentially while the other column displaying the same number till a limit is reached -
i have been trying write code users enters 2 numbers in order 2 columns. hard explain words trying achieve here example:
if user inputs a = 1 , b = 1, following table should created:
ans = 1 1 if user inputs a = 2 , b = 2:
ans = 1 1 1 2 2 1 2 2 if user inputs a = 2 , b = 5:
ans = 1 1 1 2 1 3 1 4 1 5 2 1 2 2 2 3 2 4 2 5 for other values of a , b, matrix should constructed according above shown sequence.
this can achieved straight-forward use of repelem , repmat:
[repelem((1:a).',b),repmat((1:b).',a,1)] a more elegant way using meshgrid , reshape after:
[a,b] = meshgrid(1:a,1:b); [a(:),b(:)] let's create anonymous function , test first approach:
>> fun = @(a,b) [repelem((1:a).',b),repmat((1:b).',a,1)]; >> fun(1,1) ans = 1 1 >> fun(2,2) ans = 1 1 1 2 2 1 2 2 >> fun(2,5) ans = 1 1 1 2 1 3 1 4 1 5 2 1 2 2 2 3 2 4 2 5
Comments
Post a Comment