Creating a new column in a table using if condition and equation

28 views (last 30 days)
Hi I have a table with daily data for a year: 365 rows x 4 columns. I need to create a new column which is defined by a function that I will show below and takes the data from other columns in the table.
For example lets say the columns of the table are labelled: A,B,C,D and the new column would be E
If D<1.2 then E=1
If D>6.5 then E=0.23
anything else E=1.18exp(-0.18*D)
This is what I have so far but the new column is only doing the last calculation and isnt following my limit values.
T = readtable('Data.csv');
if T.D <1.2
T.E = 1.0;
elseif T.D >6.5
T.E = 0.23;
else T.E = 1.18*exp(-0.18*T.D);
end
disp(T)

Accepted Answer

Stef1998
Stef1998 on 26 Nov 2021
I actually was able to find a solution for this issue for anyone else with similar problems:
unless there is another solution I missed this is how I was able to solve it-
if statements won't do the entire trick, indexing is required
T{:,'E'} = 1.18*exp(-0.18*T{:,'D'});
idx = T{:,'D'} < 1.2;
T{idx,'E'} = 1.0;
idx2 = T{:,'D'} > 6.5;
T{idx2,'E'} = 0.23;
  3 Comments
Stef1998
Stef1998 on 26 Nov 2021
Thank you Peter! When I try to repeat the steps above where 2 functions would be necessary for the new variable I run into an error that the size of the left and right do not match, would you know where I am making a mistake for this? I tried 3 different approaches with no success, For instance:
%Method 1
T.F = 1000 * (2834.1 - 0.29 * T.B - 0.004 * T.B.^(2.0));
idx3 = T.B >= 0;
T.F(idx3) = 1000 * (2501 - 2.36 * T.B);
%Method 2
idx3 = T.B < 0;
T.F(idx3) = 1000 * (2834.1 - 0.29 * T.B - 0.004 * T.B.^(2.0));
idx4 = T.B >= 0;
T.F(idx4) = 1000 * (2501 - 2.36 * T.B);
%Method 3
idx3 = T{:,'B'} < 0;
T{idx3,'F'} = 1000 * (2834.1 - 0.29 * T{:,'B'} - 0.004 * T{:,'B'}.^(2.0));
idx4 = T{:,'B'} >= 0;
T{idx4,'F'} = 1000 * (2501 - 2.36 * T{:,'B'});
Peter Perkins
Peter Perkins on 28 Nov 2021
I would think you would want
T.F(idx3) = 1000 * (2501 - 2.36 * T.B(idx3))
If T.F and T.B are in one table, they have the same size, but T.F(idx3) is shorter. You need to assign from the same subset of T.B, I think.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!