필터 지우기
필터 지우기

Writing cells into a .dat file?

조회 수: 10 (최근 30일)
Ali Almakhmari
Ali Almakhmari 2023년 8월 11일
편집: C B 2023년 8월 11일
I have a .mat file that looks like this:
A movement in the row-driection (down) means a new line in the .dat file and a movement in the column direction (right) indicates that between each cell is a comma. So the final file would look something like this (dont mind the spacing in front of each line):
I tried using the writecell command to wirte this .dat file from the .mat file but I failed. I am hoping someone can help me achieve it. I attached the .mat file as a reference.

채택된 답변

C B
C B 2023년 8월 11일
편집: C B 2023년 8월 11일
Let me know if this is what you wanted and if anything is not clear in
load('files.mat')
numRows = size(files, 1);
concatenatedRows = cell(numRows, 1);
startcomma = false;
for i = 1:numRows
row = files(i, :);
rowStr = cellfun(@convertToString, row, 'UniformOutput', false);
rowStr(cellfun('isempty', rowStr)) = [];
if strcmp(rowStr{1}(1), '$')
startcomma = true;
end
if startcomma
if ~strcmp(rowStr{1}(1), '$')
if strcmp(rowStr{end}, '$')
concatenatedRows{i} = strjoin(rowStr, ',');
concatenatedRows{i} = [' ' , concatenatedRows{i}];
else
concatenatedRows{i} = [strjoin(rowStr, ','), ','];
concatenatedRows{i} = [' ' , concatenatedRows{i}];
end
else
concatenatedRows{i} = strjoin(rowStr, ' ');
concatenatedRows{i} = [' ' , concatenatedRows{i}];
end
else
concatenatedRows{i} = strjoin(rowStr, ' ');
end
if strcmp(rowStr{end}, '$')
startcomma = false;
end
end
filename = 'output.dat';
fid = fopen(filename, 'w');
for i = 1:numRows
fprintf(fid, '%s\n', concatenatedRows{i});
end
fclose(fid);
function out = convertToString(in)
if isnumeric(in)
out = num2str(in);
elseif islogical(in)
out = char(string(in));
else
out = char(in);
end
end
  댓글 수: 2
Ali Almakhmari
Ali Almakhmari 2023년 8월 11일
편집: Ali Almakhmari 2023년 8월 11일
Thank you so much. This is almost what I want, what is missing is the fact that the comma between each cell in a row are missing. So you will see that the output.dat doesn't match the picture I attached in terms of the commas, instead of the commas, output.dat put spaces. Can you edit the code please?
C B
C B 2023년 8월 11일
updated code for comma and space at start.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by