从Matlab中的下面的“for loops”,我想提取150个“规则”矩阵(每个尺寸1200 * 5),而“数据”有1200 * 5维,“Var1C”150 * 5和“Var2C” “有150 * 5维度。 感谢。
for i = 1:150,
for j=1:5,
for i1=1:1200,
if Var1C(i,j)==1 & Data(i1,j)<Var2C(i,j) | Var1C(i,j)==2 & Data(i1,j)>=Var2C(i,j)
Rules = 0;
else
Rules = 1;
end
end
end
end
答案 0 :(得分:3)
嗯,你只需拥有一个150 x 1200 x 5的矩阵:
Rules = zeros(150,1200,5); % pre-allocate matrix
for i = 1:150,
for j=1:5,
for i1=1:1200,
if Var1C(i,j)==1 & Data(i1,j)<Var2C(i,j) | Var1C(i,j)==2 & Data(i1,j)>=Var2C(i,j)
Rules(i,i1,j) = 0;
else
Rules(i,i1,j) = 1;
end
end
end
end
答案 1 :(得分:0)
为什么不使用bsxfun对这个可怕的嵌套循环进行矢量化?
Rules = bsxfun( @and, permute( Var1C, [1 3 2] ) == 1,...
bsxfun( @lt, permute( Data, [3 1 2 ] ), permute( Var2C, [1 3 2] ) ) ) | ...
bsxfun( @and, permute( Var1C, [1 3 2] ) == 2,...
bsxfun( @ge, permute( Data, [3 1 2 ] ), permute( Var2C, [1 3 2] ) ) ) ;