Reputation: 45
I wrote a code to extract lithology depth information from a borehole data.
Each lithology has two depths: top depth and bottom depth. They look like this:
Sandstone '830.212' '828.222'
Siltstone '832.612' '830.922'
each type of lithology has different dimensions of cell.
sandstone 12*2 cell
coal 1*2 cell
mudstone 14*2 cell etc.
How can I write these information to a text file?
It seems like I could use dmwrite, but I'd have problem forming a datamatrix because each type of rock has two depths.
How can this be done?
Upvotes: 1
Views: 1493
Reputation: 2571
For cell arrays of strings, I use the following simple function, which is placed in C:\Users\NAME\Documents\MATLAB\@cell
or the equivalent userpath on your platform (~/Documents/MATLAB/@cell
). The @cell
name informs MATLAB that the functions within @cell
are to be used with cell arrays only.
function csvwrite(fileName,cellArray)
fid = fopen(fileName,'w');
for i=1:size(cellArray,1)
fprintf(fid,'%s,',cellArray{i,1:end-1});
fprintf(fid,'%s\n',cellArray{i,end});
end
fclose(fid);
If you need traditional Windows/DOS line endings, replace "\n" with "\n\r" in the second fprintf
call. You might also replace "," in the first call with "\t" if you want tabs.
For numerical arrays you can use the csvwrite
function included with MATLAB.
If you have to use cell arrays with mixed data types, the function must be modified to accept an array for format specifiers.
function csvwrite(fileName,cellArray,spec)
fid = fopen(fileName,'w');
for i=1:size(cellArray,1)
fprintf([spec '\n'],cellArray{i,1:end});
end
fclose(fid);
For an array with rows similar to: { 1 3 5 'string1' string2' }
you would use spec = '%d,%d,%s,%s'
, for example.
Based on these examples you could write a more sophisticated function which tests the type of the data in each cell and constructs a format string to match, in case you will have completely unknown array contents.
Upvotes: 1