replace a string by a cell array in a text file
Show older comments
Hi, I have a text file 'TEXT.txt' with the following format
DATA
[$1]
/
I would like to use strrep('TEXT.txt', '[$1]', A) in such a way to replace [$1] by cell array A. For instance suppose I have a 2x1 cell array A where
A{1}
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
37 38 39 40 41 42
43 44 45 46 47 48
49 50 51 52 53 54
55 56 57 58 59 60
61 62 63 64 65 66
67 68 69 70 71 72
73 74 75 76 77 78
79 80 81 82 83 84
85 86 87 88 89 90
91 92 93 94 95 96
and A{2} is
97 98 99 100
My TEXT.txt file after replacemnt should look like this:
DATA
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
37 38 39 40 41 42
43 44 45 46 47 48
49 50 51 52 53 54
55 56 57 58 59 60
61 62 63 64 65 66
67 68 69 70 71 72
73 74 75 76 77 78
79 80 81 82 83 84
85 86 87 88 89 90
91 92 93 94 95 96
97 98 99 100
/
1 Comment
H R
on 4 Jan 2016
Answers (2)
What is the class of the contents of A{1}? Is it a string or a double matrix?
If it is a string:
FileStr = fileread(FileName);
FileStr = strrep(FileStr, '[$1]', A{1});
fid = fopen(FileName, 'w');
if fid == -1, error('Cannot open file: %s', FileName); end
fwrite(fid, FileStr, 'char');
fclose(fid);
If A{1} contains a double array, convert it to a string at first:
S = size(A{1});
Fmt = [repmat('%g\t', 1, S(2) - 1), '%g\n'];
B = sprintf(Fmt, A{1}.');
The rest equals the above solution except for:
FileStr = strrep(FileStr, '[$1]', B);
Walter Roberson
on 4 Jan 2016
BothA = [ reshape(A{1}.', 1, []), A{2} ];
%print the data up to 6 up line
fprintf(fid, '%d %d %d %d %d %d\n', BothA);
if mod(length(BothA,6) ~= 0
%if there was not an even multiple of 6 then the final \n was not emitted
fprintf(fid, '\n');
end
Categories
Find more on Cell Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!