Nested loop problem with the second index
显示 更早的评论
Dear all,
the following code does not work well for index j > 1. I have two vectors cpx = 1-by-n and cpy = 1-by-m.
I would a new matrix cp with n-by-m rows and 2 columns with all the possible permutations of the elements in cpx and cpy. Where is the mistake?
for i = 1:length(cpx)
for j = 1:length(cpy)
cp(i.*j,:) = [cpx(i) cpy(j)];
end
end
The results are fine till row 55, so that the first cicle for i = 1:55 and j = 1 works well, then the results are incomprehensible.
采纳的回答
更多回答(2 个)
cp = zeros(length(cpx)*length(cpy),2);
row = 0;
for i = 1:length(cpx)
for j = 1:length(cpy)
row = row + 1;
cp(row,:) = [cpx(i) cpy(j)];
end
end
The simple MATLAB way:
>> cpx = [1,3,5,7];
>> cpy = [22,44,66];
>> [X,Y] = ndgrid(cpx,cpy);
>> M = [X(:),Y(:)]
M =
1 22
3 22
5 22
7 22
1 44
3 44
5 44
7 44
1 66
3 66
5 66
7 66
类别
在 帮助中心 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!