How do I save a cell array that has both text and numeric data?

I have a data set where I would like to extract alphanumeric data to a text file. E.g. here is one 1x6 cell array:
37 0 240 0.436 'cat dog mouse' 10
I would like to save this data into a text file but I cannot do that with the fprintf command since it contains alphanumeric data. How do I do this?

 採用された回答

dpb
dpb 2016 年 11 月 15 日

1 投票

>> fmt=[repmat('%5d',1,3) '%8.4f ' '%s %5d\n'];
>> fprintf(fmt,c{:})
7 0 240 0.4360 cat dog mouse 10
>>

その他の回答 (1 件)

Image Analyst
Image Analyst 2016 年 11 月 15 日

1 投票

Here's one way:
ca = {37, 0, 240, 0.436, 'cat dog mouse', 10}
fid = open(filename, 'wt'); % File on disk
% fid = 1; % Command window.
fprintf(fid, '%f, %f, %f, %f, %s, %d\n', ca{:});
close(fid);

4 件のコメント

T Shep
T Shep 2016 年 11 月 15 日
Thank you! Both solutions work great! I see now that I was denoting the numeric data with %d instead of %f
Image Analyst
Image Analyst 2016 年 11 月 15 日
You need %f for numbers with fractional parts. You can use %f for integers also but %d works for integers only and %d is what I use if I know for certain the numbers are pure integers. Using %d for fractional numbers won't work - you need %f for them.
T Shep
T Shep 2016 年 11 月 16 日
I see. I think I am getting the hang of it. What if I want to now open up that text file so that each number is in a separate cell and the string 'cat dog mouse' is back in it's own cell (without commas)? i.e. read it in so that I am back to: 37 0 240 0.436 'cat dog mouse' 10
Do I just use....
textread(fid, '%f, %f, %f, %f, %s,%f,%f, %d\n')
Image Analyst
Image Analyst 2016 年 11 月 16 日
I don't know. You could always try it. I think they recommend textscan() now instead of textread(). Or you could use fgetl() to get just one line and then use textscan() or sscanf() on just that line.
You might also be able to use importdata() or readtable(). See which function lets you read it in with the least fuss.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Import and Export についてさらに検索

質問済み:

2016 年 11 月 15 日

コメント済み:

2016 年 11 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by