필터 지우기
필터 지우기

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

조회 수: 28 (최근 30일)
Stef1998
Stef1998 2021년 11월 25일
댓글: Peter Perkins 2021년 11월 28일
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)

채택된 답변

Stef1998
Stef1998 2021년 11월 26일
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
Stef1998
Stef1998 2021년 11월 26일
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 2021년 11월 28일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by