Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 一种有两列的表,其中一列按顺序递增,而另一列显示相同的数字,直到达到某个限制为止_Matlab - Fatal编程技术网

Matlab 一种有两列的表,其中一列按顺序递增,而另一列显示相同的数字,直到达到某个限制为止

Matlab 一种有两列的表,其中一列按顺序递增,而另一列显示相同的数字,直到达到某个限制为止,matlab,Matlab,我一直在尝试编写一个代码,其中用户输入两个数字以获得两列。很难用语言来解释我试图实现的目标,因此这里有一个例子: 如果用户输入a=1和b=1,则应创建下表: ans = 1 1 如果用户输入a=2和b=2: ans = 1 1 1 2 2 1 2 2 如果用户输入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 对于a和b的其他值,应按

我一直在尝试编写一个代码,其中用户输入两个数字以获得两列。很难用语言来解释我试图实现的目标,因此这里有一个例子:

如果用户输入
a=1
b=1
,则应创建下表:

ans =

1    1
如果用户输入
a=2
b=2

ans =

1    1
1    2
2    1
2    2
如果用户输入
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

对于
a
b
的其他值,应按照上述顺序构造矩阵。

这可以通过使用直接实现:

[repelem((1:a).',b),repmat((1:b).',a,1)]

一种更优雅的方法是使用并在以下情况下对其进行重塑:

[A,B] = meshgrid(1:a,1:b);
[A(:),B(:)]

让我们创建一个匿名函数并测试第一种方法:

>> 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
这里有另一种方法 例如
a=2
b=5

 A(1:b*a,1) = reshape(mtimes((1:a).',ones(1,b)).',1,b*a)
 A(1:b*a,2) = reshape(mtimes((1:b).',ones(1,a)),1,b*a)
A =

     1     1
     1     2
     1     3
     1     4
     1     5
     2     1
     2     2
     2     3
     2     4
     2     5
只有一个逻辑,在下面的代码中定义了行大小和列大小的矩阵a和列大小b

>> mtimes((1:a).',ones(1,b))

ans =

     1     1     1     1     1
     2     2     2     2     2
下一步只需通过转置对
a
的矩阵按列和
b
的矩阵按行进行重塑

A(1:b*a,1) = reshape(mtimes((1:a).',ones(1,b)).',1,b*a)
A(1:b*a,2) = reshape(mtimes((1:b).',ones(1,a)),1,b*a)