writing to an array

조회 수: 32 (최근 30일)
Baba
Baba 2011년 11월 15일
I have some code that writes data in a column to a file. Instead of writing this to a file, I'd like to write to an Array A and have it stored in MATLAB workspace:
f = fopen ([FileName], 'data');
% write text data
fprintf (f, '%.5f\n', a);
% close file
fclose(f);

답변 (3개)

Fangjun Jiang
Fangjun Jiang 2011년 11월 15일
If you want to assign the value of the vector or matrix "a" to a particular column of the matrix variable "A", then
A(:,ColumnNumber)=a(:)
Of course, the number of rows in "A" needs to be the same as the number of elements in "a".
UPDATE
For example:
A=rand(9)
a=magic(3)
A(:,2)=a(:)
If you have variable "a" in the workspace, it is already "saved" in a sense that you don't need to "write" it to another variable to "save" it.
If for some reason, the value of "a" is going to be changed during data processing and you want to keep a copy of the value of "a", simply assign it to a new variable, such as a_backup=a;
You can save the numeric data "a" in a .mat file or .txt file using save().
save 'test.mat' a
save 'test.txt' a -ascii
  댓글 수: 4
Baba
Baba 2011년 11월 15일
Here is my code, I want to avoid writing to ascii and instead jsut save to visible workspace variable
files = dir('*.bin');
B = [];
for i=1:length(files)
A = [];
fprintf ('%s...\n', files(i).name);
[d] = bintoasciconverter(files(i).name);
a = d(:,1);
A = [A, a];
f = fopen (Data], 'a');
fprintf (f, '%.5f\n', a);
fclose(f);
B = [B; A];
end
Fangjun Jiang
Fangjun Jiang 2011년 11월 15일
A=[] is inside the for-loop so A is re-set at every iteration.
The way you concatenate to construct A is fine. But B is questionable as it contains many duplicated data carried over by A.

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


Naz
Naz 2011년 11월 15일
For .txt file this should work:
A=importdata('Name.txt');
A=bin2dec(A); %not sure that this line will work
save (name,'A');
  댓글 수: 2
Baba
Baba 2011년 11월 15일
i'd like to save the data before it gets written to a file. my point is to eliminate writing to a txt
Naz
Naz 2011년 11월 15일
So, what is your initial data that you want to write to the matrix?

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


Walter Roberson
Walter Roberson 2011년 11월 15일
txtdata = sprintf(f, '%.5f\n', a);
That would give you a character row vector with linefeed (char(10)) in the vector at each position that a new line to be started.
If you prefer this to be converted to a cell array:
txtdata = regexp( sprintf(f, '%.5f\n', a), '\n', 'split');
Note: this particular cell array will end with an empty string because the \n at the end of the final number will trigger a split between that final number and the end of the string. You can remove that empty string.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by