在Matlab中迭代一个向量到另一个向量
我正在尝试为学校作业创建算法.基本上我有两个向量
I am trying to create an algorithm for a school assignment. Basically I have two vectors
A=[1 5]
(称其为2个价格)
B=[1 2 3 4 5 6 7 8 9 10; 1 2 3 4 5 6 7 8 9 10...]
B是2D矩阵,并在许多行中延续相同的模式.我想在此B数组中添加第三个维度,其中包含A的所有可能(价格)组合.例如
B is a 2D matrix and continues the same pattern for many rows. I want to add a third dimension to this B array with all possible (price) combinations of A. For example
现在只看一行并原谅我的符号,但是我试图显示所有列,然后显示其后面的多个维度.
Looking at a single row for now and forgive my notation but I am trying to show all columns and then multiple dimensions behind it.
B(row 1)=[1 2 3 4 5 6 7 8 9 10; 1 1 1 1 1 1 1 1 1 1]
B(row 1)=[1 2 3 4 5 6 7 8 9 10; 1 1 1 1 1 1 1 1 1 5]
B(row 1)=[1 2 3 4 5 6 7 8 9 10; 1 1 1 1 1 1 1 1 5 1]
B(row 1)=[1 2 3 4 5 6 7 8 9 10; 1 1 1 1 1 1 1 1 5 5]
这最后一部分基本上以二进制进行计数,直到1和5的所有组合都作为第三维.我对如何开始这个项目一无所知.有什么想法吗?
This last section is basically counting in binary until all combinations of 1 and 5 exist as a third dimension. I'm at a loss with how to begin this project. Any ideas?
谢谢大家.
添加更多细节.我需要路易斯建议的内容,但格式略有不同.我的B矩阵看起来真的像这样:
To add a bit more detail. I need what Luis has suggested but in a slightly different format. My B matrix really looks like this:
D(:,:,1)=
0 2 3 4 5 6 7 8 9 10
1 0 3 4 5 6 7 8 9 10
1 2 0 4 5 6 7 8 9 10
1 2 3 0 5 6 7 8 9 10
1 2 3 4 0 6 7 8 9 10
1 2 3 4 5 0 7 8 9 10
1 2 3 4 5 6 0 8 9 10
1 2 3 4 5 6 7 0 9 10
1 2 3 4 5 6 7 8 0 10
1 2 3 4 5 6 7 8 9 0
然后,我需要每个3D图层都具有相同的重复图案.最终,D矩阵应为< 10x10x1025>
I then need each 3rd dimensional layer to have the same repeating pattern. Ultimately the D matrix should be <10x10x1025>
D(:,:,2)=
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
...
D(:,:,3)=
1 1 1 1 1 1 1 1 1 1 5
1 1 1 1 1 1 1 1 1 1 5
...
D(:,:,4)=
1 1 1 1 1 1 1 1 1 5 1
1 1 1 1 1 1 1 1 1 5 1
...
我假设B
是向量,而不是矩阵.
I'm assuming B
is a vector, not a matrix.
此代码使用 ndgrid
和逗号-分隔的列表(从单元格数组生成)作为输出.然后,它沿着三维尺寸被重复的B
行污染.
This code generates all combinations of values of A
, using ndgrid
with a comma-separated list (generated from a cell array) as output. It then contatenates along third dimension with the repeated rows of B
.
B = 1:10; %// example data. Vector of arbitrary length
A = [1 5]; %// example data. Vector of arbitrary length
s = numel(B);
t = numel(A);
C = cell(1,s);
[C{:}] = ndgrid(A);
C = cat(s+1, C{:});
C = fliplr(reshape(C, t^s, s));
D = cat(3, repmat(B,t^s,1), C); %// desired result
如果B
是矩阵,则要获取已编辑问题的结果,可以按以下方式修改代码:
If B
is a matrix, to obtain the result of your edited question you can modify the code as follows:
B = [1:10; 2:11; 3:12]; %// example data. Matrix of arbitrary size
A = [1 5]; %// example data. Vector of arbitrary length
s = size(B,2);
t = numel(A);
C = cell(1,s);
[C{:}] = ndgrid(A);
C = cat(s+1, C{:});
C = fliplr(reshape(C, t^s, s));
C = repmat(permute(C, [3 2 1]), [size(B,1) 1 1]);
D = cat(3, B, C); %// desired result