Effacer les filtres
Effacer les filtres

How can I create a new column in a table via if function?

2 vues (au cours des 30 derniers jours)
Jennifer Pichl
Jennifer Pichl le 23 Mar 2018
Commenté : Jennifer Pichl le 26 Mar 2018
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

Réponse acceptée

David Fletcher
David Fletcher le 23 Mar 2018
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

Plus de réponses (1)

Peter Perkins
Peter Perkins le 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).

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by