Write cell array, table into text file?

조회 수: 13 (최근 30일)
Peter Fang
Peter Fang 2022년 4월 23일
편집: Stephen23 2022년 4월 23일
hello again guys.
I have 1 question: I used cell2table to be able to use writetable, but the output data stick together, it doesn't match the model given by the teacher.
My result name: exe.txt
The result the teacher needs: result_example.txt
I'm asking myself, if I concatenate the words in cell array H will it solve the problem?
I will leave the resulting file and image below, including the m file of the function.
Hope you can help. Thank you.
P/s: I use R2018a
  댓글 수: 1
Stephen23
Stephen23 2022년 4월 23일
편집: Stephen23 2022년 4월 23일
@Peter Fang: please upload log.txt by clicking the paperclip button.
Does your teacher really need a fixed width file separated by varying numbers of tabs? It would be much much simpler if they accepted a fixed-width file separated by space characters.

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

채택된 답변

Stephen23
Stephen23 2022년 4월 23일
편집: Stephen23 2022년 4월 23일
Fake data just for testing the code:
dtm = datetime(2021,3,[1;2;31],'Format','dd-MM-yyyy')
dtm = 3×1 datetime array
01-03-2021 02-03-2021 31-03-2021
num = [15;10;2]
num = 3×1
15 10 2
Connvert data (from table or whatever you have) into one cell array:
tmp = num2cell(reshape(dtm,1,[]));
tmp(2,:) = num2cell(num);
Header:
hdr = {'Ngay','So luong'};
hdr = regexprep(hdr,' ','\a');
Now print fixed-width text using tab separator:
str = [...
sprintf('%-16s%-s\n',hdr{:}),...
sprintf('%-16s%-u\n',tmp{:})];
str = regexprep(str,' {1,4}','\t');
str = regexprep(str,'\a',' ');
[fid,msg]= fopen('result.txt','wt');
fprintf(fid,'%s',str);
fclose(fid);
Check file content:
type result.txt
Ngay So luong 01-03-2021 15 02-03-2021 10 31-03-2021 2
It is a shame that FPRINTF does not have an option for padding with tabs.
  댓글 수: 1
Peter Fang
Peter Fang 2022년 4월 23일
Thank you <3. I tried it and it worked.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 4월 23일
Try writecell().
  댓글 수: 1
Peter Fang
Peter Fang 2022년 4월 23일
Impossible. I tried but it doesn't exist in 2018 version

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

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by