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

采纳的回答

David Fletcher
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
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).

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by