How can I create a new column in a table via if function?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Jennifer Pichl
el 23 de Mzo. de 2018
Comentada: Jennifer Pichl
el 26 de Mzo. de 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
0 comentarios
Respuesta aceptada
David Fletcher
el 23 de Mzo. de 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
Más respuestas (1)
Peter Perkins
el 24 de Mzo. de 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).
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!