Home > Mobile >  Avoid Matlab Loop for adding value
Avoid Matlab Loop for adding value

Time:10-29

I would like to avoid the for loop in my code, since that is so pretty computationally intensive.

I search my data frame for a variable, if the variable is 0 the amount 1000 should be added to another variable. The same if the variable is 1.

for i=1:height(dataframe)
if df.status(i) ==0
    df.Number(i) = df.Number(i) 10000;
else if df.status(i) ==1
        df.Number(i) = df.Number(i) 20000;
    end
end
end

I am very grateful for any advice- Tim

CodePudding user response:

Assuming your loop visits each element in df.Number and df.status is also the same size, then you can summarize your code as

df.Number = df.Number   10000   (df.status==1) * 10000;

A logical value (Boolean) in MATLAB always has the value of either 0 or 1, and comparing status==1 ensures a logical value.

If df.status is a logical, you can skip the comparison: 10000 df.status * 10000.

CodePudding user response:

I don't know the data type of the data frame but you can approach this by getting the index when that condition is reached.

% Generate a simple dataframe
dataframe = [0 0 1 1 2 2 1 0 5]';

% Get 0s index and add 10,000 to those indexes
idx_0 = dataframe == 0;
dataframe(idx_0) = dataframe(idx_0)   10000;
% Get 1s index and add 20,000 to those indexes
idx_1 = dataframe == 1;
dataframe(idx_1) = dataframe(idx_1)   20000; 
  
% Print dataframe variable
dataframe
  • Related