How can I save a series of variables in workspace to a txt file?

조회 수: 5 (최근 30일)
Marty Dutch
Marty Dutch 2013년 10월 3일
댓글: Marty Dutch 2013년 10월 4일
Hi all,
I want to save a bunch of variables (data1, data2 etc) to a textfile (alldata.txt). The code below is a simplified version but it makes the problem clear, since the saved data in the textfile is not correct.
data1 = 1
data2 = 2
data7 = 3
data10 = 5
for i = 1:10
try
fid = fopen('alldata.txt','w');
x = (sprintf('data%d', i));
fprintf(fid,'%d\n',x);
fclose(fid);
catch
continue;
end
end
Tthis is the output in alldata.txt, which is wrong:
100
97
116
97
49
48
Is there anybody who can help me?
ps. I dont want to make use of the option: save() with the -ascii flag, because I want to be able to do some text formatting.

채택된 답변

Walter Roberson
Walter Roberson 2013년 10월 3일

추가 답변 (1개)

dpb
dpb 2013년 10월 3일
data1 = 1;
data2 = 2;
data7 = 3;
data10 = 5;
Don't do this; as you've discovered "there be dragons". Use
data=zeros(10,1); % set size as needed...
data(1)=1;
data(2) = 2;
data(7) = 3;
data(10) = 5;
instead. Then write the array members desired.
Or, of course, if there are a large number of missing indices, you can use named fields in a structure to provide specific ones instead of a full array.
Matlab works best if you don't try to create such named variables as you show initially--falling into the (common; don't think you're the only/first with the above idea) trap above is counterproductive in almost every case.
  댓글 수: 1
Marty Dutch
Marty Dutch 2013년 10월 4일
It works now. The code below does what I need it to do! Import data stored in txt files, then calculate the mean, and put these in one matrix.
clear all
clc
fileDirectory = '/dir'; %directory containing .txt files
files = dir(fullfile(fileDirectory,'*.txt'));
disp(numel(files)); %display filenames
for i = 1 : numel(files)
fileNameIn = files(i).name;
data = load (fileNameIn);
disp(fileNameIn);
t(i, 1:1) = mean(data);
end;

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by