Find a string in a text file and replace it by elements of a matrix

1 view (last 30 days)
I have a text file str = 'C:\KR.txt'. somewhere in the file I have the following:
-- this is what to change
[$1]
/
I want a code to find [$1] and replace it with element of an array A. For example suppose that A has 3 columns and 4 rows A= [1 2 3; 4 5 6; 7 8 9; 10 11 12]. So I should have this
-- this is what to change
1 2 3
4 5 6
7 8 9
10 11 12
/
I tried to use this
str = strrep(str, '[$1]',mat2str(A));
but the results are not as I expect. Can you please suggest ? Thank you

Accepted Answer

Cedric
Cedric on 4 Jul 2014
Edited: Cedric on 4 Jul 2014
Instead of mat2str(A), use the following
Astr = sprintf( [repmat('%d ', 1, size(A, 2)), '\r\n'], A.' ) ;
str = strrep( str, '[$1]', Astr ) ;
Or, the more versatile (because you leave it to NUM2STR to use the correct format)
Astr = sprintf( [num2str(A), repmat('\r\n', size(A, 1), 1)].' ) ;
str = strrep( str, '[$1]', Astr ) ;
Note that you might want to remove the \r if you are working in a UNIX-like environment.
  1 Comment
Cedric
Cedric on 4 Jul 2014
Edited: Cedric on 4 Jul 2014
I may have edited my answer after you read it, because when I saved the edit you had already accepted the answer. Sorry for this.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!