Ordering the name of excel files from short to longer length

조회 수: 1 (최근 30일)
Adi Purwandana
Adi Purwandana 2023년 9월 12일
댓글: Adi Purwandana 2023년 9월 12일
Hello everyone,
I have a script which split an excel file into several excel files using this code:
data = readtable('dataset.xlsx');
stations = unique(data.Station);
for i=1:numel(stations)
x = data(data.Station==stations(i), :);
writetable(x,"Sta_"+num2str(stations(i))+".xlsx");
end
FYI, each file created using such code has different lengths. For example:
Sta_1 --> 8 rows;
Sta_2 --> 3 rows;
Sta_3 --> 6 rows.
My question is... is it possible to order from the shorter length to longer length when using writable function?
So, I want the file names is ordered based on the length of the file, i.e.,
Sta_1 --> file with 3 rows;
Sta_2 --> file with 6 rows;
Sta_3 --> file with 8 rows.
Thanks

채택된 답변

kei hin
kei hin 2023년 9월 12일
편집: kei hin 2023년 9월 12일
Check the length inside the for loop and store the sorted result in variables, then use the writetable outside the for loop.
  댓글 수: 3
kei hin
kei hin 2023년 9월 12일
code like this. It may not be exactly what you need.
data = readtable('dataset.xlsx');
stations = unique(data.Station);
tmp = {};
for i=1:numel(stations)
x = data(data.Station==stations(i), :);
if isempty(x)
continue; %empty skip
end
tmp{end+1,1} = x;
[row,col] = size(x);
tmp{end,2} = row; % length, for sort
end
result = sortrows(tmp,2); % sort by length
for i=1:length(result)
writetable(result{i,1},"Sta_"+num2str(stations(i))+".xlsx");
end
Adi Purwandana
Adi Purwandana 2023년 9월 12일
It perfectly works! Thank you very much @kei hin!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by