How can I create a new column in a table via if function?
조회 수: 1 (최근 30일)
이전 댓글 표시
I have a 45060x3 timetable, where the value kW ranges form 0 to 800. Now I want to create a new column (charger) which is definded by the if function down below. However when I execute this code, it creates a column (charger) where all the values equal the ones in kW even there are a lot of values which fullfill the if statement. Can you tell me what is the problem with this code? Or is there a other way to get the values I want for the new column?
if T3DHM18.kW<=400
T3DHM18.charger=T3DHM18.kW+150 %%Take the values form T3DHM18.kW and add 150
else
T3DHM18.charger=T3DHM18.kW %%if x>400 than it is same as T3DHM18.kW
end
댓글 수: 0
채택된 답변
David Fletcher
2018년 3월 23일
By way of a smaller example -
%Create dummy table for the purpose of example
tbl=table()
tbl.KW=(1:10)'
%Copy KW column to a new charger column
tbl.Charger=tbl.KW
%Create indexer into the table for all rows where KW<4
ind=tbl.KW<4
%Add 150 to the rows where KW is less than 4
tbl.Charger(ind,:)=tbl.Charger(ind,:)+150
tbl =
10×2 table
KW Charger
__ _______
1 151
2 152
3 153
4 4
5 5
6 6
7 7
8 8
9 9
10 10
추가 답변 (1개)
Peter Perkins
2018년 3월 24일
Another possibility, similar to David's solution:
T3DHM18.charger = T3DHM18.kW + 150*(T3DHM18.kW<=400)
The problem with the original code is that the if statement is written with element-wise assignment in mind, while the assignment itself is vectorized. When given a logical vector, an if statement evaluates only the first element (for historical reasons).
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!