0

From the below "for loops" in Matlab, I want to extract 150 matrices of "Rules" (each with dimension 1200*5) whereas "Data" has 1200*5 dimension, "Var1C" 150*5 and "Var2C" has 150*5 dimension. Thanks.

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
Shai
  • 111,146
  • 38
  • 238
  • 371
Elias
  • 9
  • 1
  • 1
    [Using `i` `j` and `i1` as variable names in Matlab is not recommanded](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). `i1` can be easily confused with `1i`. – Shai Jul 17 '13 at 09:13

2 Answers2

3

Well, you could have a 150 x 1200 x 5 matrix simply by having:

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
am304
  • 13,758
  • 2
  • 22
  • 40
  • 4
    You could also replace the whole if then statement with this one line: `Rules(i,i1,j) = Var1C(i,j)==1 & Data(i1,j)=Var2C(i,j)` – Dan Jul 17 '13 at 08:48
0

Why don't you vectorize this horrible nested loop using ?

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] ) ) ) ;
Hugh Nolan
  • 2,508
  • 13
  • 15
Shai
  • 111,146
  • 38
  • 238
  • 371
  • I had to check if `bexfun` was some vectorizing function I hadn't heard of first ;) – Hugh Nolan Jul 17 '13 at 10:32
  • 1
    @HughNolan - I might apply for a "function name generator" position at mathworks... – Shai Jul 17 '13 at 10:37
  • `L=1;while (1), X=ceil(log(L)/log(26)); S=L; funcname=zeros(1,X); for (v=1:X), funcname(v) = mod(S,26); S=floor(S/26); end; funcname=char(96+funcname); if ~exist('funcname','builtin') ReportToMathworks(funcname); end; L=L+1; end` and just sit and watch the cash roll in... – Hugh Nolan Jul 17 '13 at 10:57