Can I assign names to variables in a table column?
15 views (last 30 days)
Show older comments
I am slowly teaching myself how to use matlab so I am a relatively new users. I need a little bit of help.
I have a data table that looks like this:
Position Total Impacts Impacts per Hour
______ ____________ ______________
1 1000 1.5
2 800 1.3
3 1500 1.7
The first column Position has numbers substituted in for text. The number 1 represents forwards, the number 2 represents midfielders, the number 3 represents defenders.
My question:
Is there a function that I can use where I can assign text to the number and replace the numbers with the the text counterpart so that my table looks like:
Position Total Impacts Impacts per Hour
______ ____________ ______________
Forward 1000 1.5
Midfielder 800 1.3
Defender 1500 1.7
It is not a huge deal as I can change the variables once I export to excel but it would save me some time.
Thank you for your help.
0 Comments
Answers (1)
Image Analyst
on 14 Feb 2022
Try this:
Position = [1;2;3];
TotalImpacts = [1000; 800; 1500];
ImpactsPerHour = [1.5; 1.3; 1.7];
t = table(Position,TotalImpacts,ImpactsPerHour, 'VariableNames', {'Position','TotalImpacts','ImpactsPerHour'})
Position2 = cell(height(t), 1);
for row = 1 : height(t)
if t.Position(row) == 1
Position2{row} = 'Forward';
elseif t.Position(row) == 2
Position2{row} = 'Midfielder';
elseif t.Position(row) == 3
Position2{row} = 'Defender';
end
end
t = table(Position2,TotalImpacts,ImpactsPerHour, 'VariableNames', {'Position','TotalImpacts','ImpactsPerHour'})
2 Comments
Steven Lord
on 14 Feb 2022
I would proably use a categorical array instead.
rng default
Position = randi(3, 6, 1);
TotalImpacts = randi([800, 2000], 6, 1);
ImpactsPerHour = randi([10, 20], 6, 1)./10;
t = table(Position,TotalImpacts,ImpactsPerHour, ...
'VariableNames', {'Position','TotalImpacts','ImpactsPerHour'})
t.PositionCat = discretize(t.Position, 1:4, 'categorical', ...
{'Forward', 'Midfielder', 'Defender'})
% Use the categorical variable
t(t.PositionCat == 'Forward', :)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!