Tabluate data using common terms in varaible names

1 view (last 30 days)
Is there a way to place the data below in a table with column names MLD, MOD, WG and OUT and rows by ab, ac, ad, ae, using the common terms in the varaiable names?
Table
MLD MOD WG OUT
ab
ac
ad
ae
ab_MLD = 2
ac_MLD = 5
ad_MLD = 2
ae_MLD = 5
ab_MOD = 6
ac_MOD = 3
ad_MOD = 9
ae_MOD = 4
ab_WG = 14
ac_WG = 3
ad_WG = 4
ae_WG = 1
ab_OUT = 2
ac_OUT = 6
ad_OUT = 3
ae_OUT = 5

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 25 Jun 2021
Edited: Scott MacKenzie on 25 Jun 2021
If I understand your question correctly, you want to extract the row and column names from the variable names. If so...
ab_MLD = 2
ac_MLD = 5
ad_MLD = 2
ae_MLD = 5
ab_MOD = 6
ac_MOD = 3
ad_MOD = 9
ae_MOD = 4
ab_WG = 14
ac_WG = 3
ad_WG = 4
ae_WG = 1
ab_OUT = 2
ac_OUT = 6
ad_OUT = 3
ae_OUT = 5
s = convertCharsToStrings(who);
data = [ab_MLD, ac_MLD, ad_MLD, ae_MLD; ...
ab_MOD, ac_MOD, ad_MOD, ae_MOD; ...
ab_WG, ac_WG, ad_WG, ae_WG; ...
ab_OUT, ac_OUT, ad_OUT, ae_OUT]';
r = unique(extractBefore(s, '_')); % row names
c = unique(extractAfter(s, '_')); % column names
T = array2table(data, 'rownames', r, 'variablenames', c)
T =
4×4 table
MLD MOD OUT WG
___ ___ ___ __
ab 2 6 14 2
ac 5 3 3 6
ad 2 9 4 3
ae 5 4 1 5
There are a few caveats here. The script must begin with a clean workspace and the line assigning the variable names must immediately follow the assignment statements.

More Answers (1)

Mohammad Sami
Mohammad Sami on 25 Jun 2021
You can specify the rownames property of the table.
a = array2table(zeros(4,4),'RowNames',{'ab' 'ac' 'ad' 'ae'},'VariableNames',{'MLD' 'MOD' 'WG' 'OUT'});
a{'ab','MLD'} = 2
a = 4×4 table
MLD MOD WG OUT ___ ___ __ ___ ab 2 0 0 0 ac 0 0 0 0 ad 0 0 0 0 ae 0 0 0 0
a{:,'MLD'} = [2;5;2;5]
a = 4×4 table
MLD MOD WG OUT ___ ___ __ ___ ab 2 0 0 0 ac 5 0 0 0 ad 2 0 0 0 ae 5 0 0 0
a{:,:} = [2 6 14 2; 5 3 3 6; 2 9 4 3; 5 4 1 5]
a = 4×4 table
MLD MOD WG OUT ___ ___ __ ___ ab 2 6 14 2 ac 5 3 3 6 ad 2 9 4 3 ae 5 4 1 5

Categories

Find more on Tables in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!