Adding a new column in table based on matching number from other columns in the same table

10 vues (au cours des 30 derniers jours)
Hi,
I am trying to create an additional column of 'choice', which should contain either 'air,'trian','bus', 'car' depending upon where 1 has appeared in their respective column for given row.
I am unable to write the code that searches for 1 in columns in AIR, Train, Bus, Car and append the name of the column (e.g., car in first row) to new column named as 'choice'.
Any help would be highly appreciated.
Best wishes,

Réponse acceptée

nick
nick le 13 Sep 2024
Hi Yasir,
You can use logical indexing function to allocate the value in column 'choice'.
You can iterate over each row, check which column has the value 1, and then assign the corresponding column name to the new column 'choice'. Here's a MATLAB script that illustrates the same :
T = readtable('mode_choice');
options = {'AIR', 'Train', 'Bus', 'Car'};
% Preallocate the 'choice' column with empty strings
T.choice = strings(height(T), 1);
for i = 1:height(T)
% Find the column with value 1
idx = find([T.AIR(i), T.Train(i), T.Bus(i), T.Car(i)] == 1);
% Check if any column contains 1
if ~isempty(idx)
T.choice(i) = options{idx};
end
end
disp(T);
You can refer to the following documentation to learn more about 'logical indexing':
  1 commentaire
Yasir
Yasir le 13 Sep 2024
@nick, thanks for helping out. It worked and thanks for referring to logical indexing, which i was unable to handle.
Bundle of thanks again.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Produits


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by