How can I create a new column in a table via if function?
Show older comments
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
Accepted Answer
More Answers (1)
Peter Perkins
on 24 Mar 2018
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).
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!