Hi guys, I have a simple question about how to save data. Let's suppose I have two vectors, x and y; I want to save them as a .txt file having two columns given by x and y. I want also to decide the name of the file (e.g. 'myfile.txt') and the directory of the folder where I save the file (e.g. 'C:\\User\Desktop\MyFolder\') in the code. Thank you!

 채택된 답변

Image Analyst
Image Analyst 2015년 1월 11일
편집: Image Analyst 2015년 1월 12일

0 개 추천

Try this:
% Get the name of the file that the user wants to save.
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
fid = fopen(fullFullFileName, 'wt');
if fid ~= -1
for row = 1 : length(x)
fprintf(fid, '%f, %f\n', x(k), y(k));
end
fclose(fid);
end

댓글 수: 3

I tried like this:
% Get the name of the file that the user wants to save.
x=[1 2 3 4 5];
y=[2 4 6 8 10];
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
fid = fopen(fullFileName, 'wt');
if fid ~= -1
for row = 1 : length(x)
fprintf('%f, %f\n', x(row), y(row));
end
fclose(fid);
end
and, if 'mydata' is the name of the file I want to save, it returns:
startingFolder =
C:\Users\Documents\MATLAB;
fullFileName =
C:\Users\\Desktop\MyFolder\mydata
1.000000, 2.000000
2.000000, 4.000000
3.000000, 6.000000
4.000000, 8.000000
5.000000, 10.000000
but the file 'mydata' is empty!
Try putting the file handle into fprintf:
fprintf(fid, '%f, %f\n', x(row), y(row)); % To file.
fprintf(1, '%f, %f\n', x(row), y(row)); % To command window.
aurc89
aurc89 2015년 1월 12일
Thank you !

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Setup and Configuration에 대해 자세히 알아보기

질문:

2015년 1월 11일

댓글:

2015년 1월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by