Adding a new column in table based on matching number from other columns in the same table
22 views (last 30 days)
Show older comments
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,
0 Comments
Accepted Answer
nick
on 13 Sep 2024 at 11:29
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':
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!