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

2 visualizzazioni (ultimi 30 giorni)
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,

Risposta accettata

nick
nick il 13 Set 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 Commento
Yasir
Yasir il 13 Set 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.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by