Clear Filters
Clear Filters

How to efficiently make the for loop of different dot structure compact?

3 views (last 30 days)
Dear Coder, I want to rename the the RowNames and VariableNames of a Table. In this case, I have there different table namely, Tab_Eight, Tab_SixLate and Tab_SixEarly. For example, To rename the each of the RowName and VariableName in the Tab_Eight, the following code were realize
% Rename each of the 8 rows
for i=1:8
Tab_Eight.Properties.RowNames{i} = char ((at.sub.ID ((GetPatName(i)),1)));
end
And
% To rename each of the 12 column
for i =1:12
Tab_Eight.Properties.VariableNames{i} = char ((at.sub.Shiftday ((GetCondType(i)),1)));
end
Similarly, the table Tab_SixLate and Tab_SixEarly were modified simply by changing the content in the for loop into Where
For the Tab_SixLate
for i=1:8
Tab_SixLate.Properties.RowNames{i} = char ((at.sub.ID ((GetPatName(i)),1)));
end
% And
for i =1:12
Tab_SixLate.Properties.VariableNames{i} = char ((at.sub.Shiftday ((GetCondType(i)),1)));
end
For the Tab_SixEarly
for i=1:8
Tab_SixEarly.Properties.RowNames{i} = char ((at.sub.ID ((GetPatName(i)),1)));
end
% And
for i =1:12
Tab_SixEarly.Properties.VariableNames{i} = char ((at.sub.Shiftday ((GetCondType(i)),1)));
end
As you can, the code is redundant and I need 6 For loop for the 3 tables. I wonder, how I can minimize the for loops? Note: The code is a portion of the big code. Without lost of meaning, only relevant code were shown

Accepted Answer

balandong
balandong on 2 Aug 2017
I think, this latest work-around work better than the original version.. However, I welcome any new suggestion.
sixEarly = (reshape ((result (:,1:96)),[12,8])).';
eightRoster = (reshape ((result (:,97:176)),[10,8])).';
sixLate = (reshape ((result (:,177:end)),[12,8])).';
% Do all the transformation under the function TABLECREATION
Tab_sixLate =tableCreation (at,sixLate);
Tab_sixEarly =tableCreation (at,sixEarly);
Tab_eightRoster =tableCreation (at,eightRoster);
function Table_Converted =tableCreation (at,NonConvertedCell)
Table_Converted = cell2table( NonConvertedCell ) ;
ListPat = (Table_Converted{:,1}).';
ListCondType = Table_Converted{1,:};
GetPatName = cellfun(@(v) v(1), ListPat(1,:));
GetCondType = cellfun(@(v) v(1), ListCondType(1,:));
% But still, I had to use two for loop here, mmm
for i=1:length (GetPatName)
Table_Converted.Properties.RowNames{i} = char ((at.sub.ID ((GetPatName(i)),1)));
end
for i =1:length (GetCondType)
Table_Converted.Properties.VariableNames{i} = char ((at.sub.Shiftday ((GetCondType(i)),1)));
end
end

More Answers (0)

Categories

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