名为A
,B
和C
的3个矩阵。每个矩阵都具有随机M x N
维度。但是,N
(列号)相等。从每个矩阵中随机生成1行并逐个放入新矩阵(命名为Fdata
),然后再次从每个矩阵中随机生成1行,但不能从前一个随机行重复生成并再次放入Fdata
......相应地......如果其中一个矩阵是为每一行随机生成一次而不重复,那么该行的其余部分可以再次随机重复,直到达到最大值来自其中一个矩阵的行。
如果A
是5x5的矩阵,B
是2x5的矩阵,C
是3x5的矩阵,Fdata
将是15x5矩阵
示例:
A =
6 6 4 7 8
4 7 1 6 9
3 5 8 0 1
6 5 8 1 2
9 4 2 0 1
B =
4 7 2 8 5
5 6 0 1 2
C =
1 6 4 5 1
8 6 7 1 3
3 0 4 5 8
我希望获得的最终数据是
Fdata =
4 7 1 6 9 %randomly from matrix A
5 6 0 1 2 %randomly from matrix B
1 6 4 5 1 %randomly from matrix c
6 6 4 7 8 %randomly from matrix A (but not repeated from previous randomly generated row)
4 7 2 8 5 %randomly from matrix B (but not repeated from previous randomly generated row)
3 0 4 5 8 %randomly from matrix C (but not repeated from previous randomly generated row)
3 5 8 0 1 %randomly from matrix A (but not repeated from previous randomly generated row)
4 7 2 8 5 %randomly from matrix B, repeated row because the row of matrix B is fully randomly generated
8 6 7 1 3 %randomly from matrix C (but not repeated from previous randomly generated row)
9 4 2 0 1 %randomly from matrix A (but not repeated from previous randomly generated row)
....
我应该写什么代码来获取Fdata
?
第二个问题:
假设Fdata=xlsread('abc.xls,);
原始Fdata
有5x2矩阵,在某些代码之后,Fdata
变为5x5矩阵......然后发生xlswrite('abc.xls',Fdata,'sheet2');
..错误...... ??? Index exceeds matrix dimensions
...我该如何解决这个问题?
答案 0 :(得分:0)
快速工作尝试,它可以进行优化,但需要更多细节:你做了多少次迭代?有破裂的情况吗?你总是会用三个矩阵来提供Fdata吗?
以下是代码的工作示例:
function Fdata=buildFdata
A=rand(5,5);
B=rand(2,5);
C=rand(3,5);
selectedA=[];
selectedB=[];
selectedC=[];
n=max([size(A,1) size(B,1) size(C,1)]);
Fdata=zeros(3*n,5);
for i=1:3:3*n-2
[Fdata,A,selectedA]=randomfeed(Fdata,A,selectedA,i);
[Fdata,B,selectedB]=randomfeed(Fdata,B,selectedB,i+1);
[Fdata,C,selectedC]=randomfeed(Fdata,C,selectedC,i+2);
end
end
function [Fdata,Mat,selectedMat]=randomfeed(Fdata,Mat,selectedMat,i)
if(~isempty(Mat))
index=randline(size(Mat,1));
Fdata(i,:)=Mat(index,:);
selectedMat(end+1,:)=Mat(index,:);
Mat(index,:)=[];
else
index=randline(size(selectedMat,1));
Fdata(i,:)=selectedMat(index,:);
end
end
function n=randline(nlines)
if(nlines==1)
n=1;
else
n=randi(nlines-1)+1;
end
end