Help optimize for loop in matlab

I have a double double array consisting of 1 and 0. I would like to match all the characters 1 with the character "-3" and "3", and all 0 with the character "-1" and "1" the same, Below is my code . Since my array is approximately 1 in 8 million, it takes a very long time. How to speed up the work?

[row,ll] = size(Data);
sym_zero = -1;
sym_one = -3;
for loop = 1 : row
    if Data(loop,1) == 0
        Data2(loop,1) = sym_zero;
                     if sym_zero == -1
                         sym_zero = 1;
                     else
                         sym_zero = -1;
                     end
    else
        Data2(loop,1) = sym_one;
                     if sym_one == -3
                         sym_zero = 3;
                     else
                         sym_zero = -3;
                     end
    end
end
+3
source share
4 answers

Here is a very important MATLAB optimization tip.

pre-select!

Your code much faster with simple predefinition. Just add

Data2 = zeros(size(Data));
for loop = 1: row 
...

before the cycle for.

preallocation 0.322s, . , :).

, MATLAB, .

+8

, , , :

nOnes = sum(Data);
nZeroes = size(Data,2) - nOnes;

Data2(find(Data)) = repmat([-3 3],1,nOnes/2)
Data2(find(Data==0)) = repmat([-1 1],1,nZeroes/2)

1 0 s.

+2

Thus, despite the negative signs, the equation for the output element is Data2 [loop, 1] = Data [loop, 1] * 2 + 1. So why not first do it using simple multiplication - this should be fast, since it can to be vectorized. Then create an array of half the original length of the array 1 s, half the original length of the array -1 s, call randperm on this. Then multiply by that. Everything is vectorized and should be much faster.

+1
source
[row,ll] = size(Data);
sym_zero = -1;
sym_one = -3;
for loop = 1 : row
    if ( Data(loop,1) ) // is 1
        Data2(loop,1) = sym_one;
        sym_one = sym_one * -1; // flip the sign
    else
        Data2(loop,1) = sym_zero;
        sym_zero = sym_zero * -1; // flip the sign
    end
end
0
source

Source: https://habr.com/ru/post/1743715/


All Articles