How to extract the name of the column and row from a table?

6 views (last 30 days)
I generated a code that extracts all the 2x2 submatrices from a 10x7 matrix while keeping the order. The original matrix is conveted into a table where each row and each column has a name. I want each column and row in each of the 2x2 submatrices to have its corresponding name as the original matrix 'sTable' (the same name as the original matrix). Here's my code:
Any help is appreciated!
clear
clc
m=rand(10,7)
rowNames = {'C1','C2','C3','C4','C5','C6','C7','C8','C9','C10'};
colNames = {'N1','N2','N3','N4','N5','N6','N7'};
sTable = array2table(m,'RowNames',rowNames,'VariableNames',colNames);
[r, c]= size(m);
sub= {};
for s=1:r-1
for n=s+1:r-s
for j=1:c
for i=j+1:c
sub{end+1}=m([s n],[j i]);
end
end
end
end

Accepted Answer

Walter Roberson
Walter Roberson on 27 Feb 2023
clear
clc
m=rand(10,7)
m = 10×7
0.1560 0.2505 0.3283 0.8692 0.8898 0.7594 0.4726 0.3797 0.1740 0.4700 0.0300 0.7172 0.8973 0.1930 0.6007 0.5831 0.7201 0.2603 0.6695 0.7427 0.4151 0.0461 0.6603 0.0917 0.4088 0.9712 0.0632 0.7082 0.1878 0.1907 0.8757 0.4067 0.3558 0.3893 0.6848 0.4975 0.0212 0.7092 0.6630 0.6808 0.0573 0.1626 0.0266 0.7145 0.1033 0.5427 0.8010 0.6619 0.0915 0.4596 0.3550 0.3405 0.7694 0.4303 0.5192 0.3400 0.7754 0.6373 0.6582 0.9949 0.2097 0.5119 0.1099 0.1028 0.8856 0.7801 0.1395 0.1616 0.1428 0.5312
rowNames = {'C1','C2','C3','C4','C5','C6','C7','C8','C9','C10'};
colNames = {'N1','N2','N3','N4','N5','N6','N7'};
sTable = array2table(m,'RowNames',rowNames,'VariableNames',colNames);
[r, c]= size(m);
sub= {};
for s=1:r-1
for n=s+1:r-s
for j=1:c
for i=j+1:c
sub{end+1} = array2table(m([s n],[j i]), 'VariableNames', colNames([j i]), 'RowNames', rowNames([s n]));
end
end
end
end
sub{1}
ans = 2×2 table
N1 N2 _______ _______ C1 0.15599 0.2505 C2 0.37972 0.17396
sub{2}
ans = 2×2 table
N1 N3 _______ _______ C1 0.15599 0.32827 C2 0.37972 0.46996
sub{floor(end/2)}
ans = 2×2 table
N6 N7 ________ _______ C2 0.89735 0.193 C4 0.063207 0.70823

More Answers (0)

Categories

Find more on Tables 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!