replace a string by a cell array in a text file

1 Ansicht (letzte 30 Tage)
H R
H R am 3 Jan. 2016
Kommentiert: H R am 4 Jan. 2016
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 Kommentar
H R
H R am 4 Jan. 2016
I have a 1D number array with N numbers say A=[1,2,3,4,5,6,7,8,9,10,...100]; I have a text file 'Test.txt'. Inside the text file I have a string [$1].
Data
[$1]
/
How to replace the string [$1] with the content of the array A in such a way that the array content is written one after each other in multiple lines where only 6 space-delimited numbers are printed in each line except the last line that could be shorter than 6 numbers (depending on the size of A). After this I would like to save the file with other name say 'Test1.txt' with the following contents:
Data
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
...
/

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Jan
Jan am 3 Jan. 2016
Bearbeitet: Jan am 3 Jan. 2016
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
Walter Roberson am 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

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by