Write a matrix of strings to text file:
51 次查看(过去 30 天)
显示 更早的评论
Hi, I have the following problem. I have to write a kind of header to text file. I tried to create a matrix (rather I should say an array) but when I tried to write I get error "Error using fprintf Function is not defined for 'cell' inputs." Here is the code:
{
vect_signals={'T' '211A015' '211B035' '211A101' '211B111' '211N401' '211D411' '21411A151' '21411K152' '21411Q501_2'...
'21411Q503_2' '21411Q505_2' '21411Q507_2' '21411Q509_2' '21411Q511_2' '22411Q151' '22411Q152' '22411Q501_2'...
'22411Q503_2' '22411Q505_2' '22411Q507_2' '22411Q509_2' '22411Q511}
vect_zeros=zeros(length(vect_signals),1);
vect_Val_zeros=num2str(vect_zeros);
matrix_signals={vect_signals01; vect_Val_zeros;};
fid01=fopen('myheader.txt','w' );
for i=1:length(vect_signals01)
fprintf(fid01,'%14s %10s \n',matrix_signals{i,:});
end
fclose('all');
}
I think it suppose to work even without loop.
The final result in the text file should be:
'T' 0
'211A015' 0
'211B035' 0
'211A101' 0
........................
2 个评论
Stephen23
2015-6-25
There are several syntax errors here, such as the
{
code...
}
parentheses, and also a missing quotation mark on the last string of vect_signals. This code does not even run and it generates multiple error messages in the editor.
采纳的回答
Stephen23
2015-6-25
编辑:Stephen23
2015-6-25
Try this:
vect_signals = {'T', '211A015', '211B035', '211A101', '211B111', '211N401', '211D411',...
'21411A151', '21411K152', '21411Q501_2', '21411Q503_2', '21411Q505_2', '21411Q507_2',...
'21411Q509_2', '21411Q511_2', '22411Q151', '22411Q152', '22411Q501_2', '22411Q503_2',...
'22411Q505_2', '22411Q507_2', '22411Q509_2', '22411Q511'};
vect_out(2,:) = num2cell(zeros(size(vect_signals)));
vect_out(1,:) = vect_signals;
fid = fopen('temp.txt','wt');
fprintf(fid,'%-14s %d\n',vect_out{:});
fclose(fid);
Which generates this file:
T 0
211A015 0
211B035 0
211A101 0
211B111 0
211N401 0
211D411 0
21411A151 0
21411K152 0
21411Q501_2 0
21411Q503_2 0
21411Q505_2 0
21411Q507_2 0
21411Q509_2 0
21411Q511_2 0
... ETC
2 个评论
Stephen23
2015-6-25
And if you need the quotation marks around the strings, then simply change this line
vect_out(1,:) = vect_signals;
to this:
vect_out(1,:) = strcat('''',vect_signals,'''');
更多回答(1 个)
dpb
2015-6-25
" I get error "Error using fprintf Function is not defined for 'cell' inputs."
Yes. Cast the cell content to char() when writing...
You also need to build the vect_signals array with a delimiter between the elements; otherwise Matlab simply concatenates them into a long single string.
vect_signals={'T'; '211A015'; ...
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!