フィルターのクリア

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

1 回表示 (過去 30 日間)
H-H
H-H 2014 年 7 月 4 日
編集済み: Cedric 2014 年 7 月 4 日
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

採用された回答

Cedric
Cedric 2014 年 7 月 4 日
編集済み: Cedric 2014 年 7 月 4 日
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 件のコメント
Cedric
Cedric 2014 年 7 月 4 日
編集済み: Cedric 2014 年 7 月 4 日
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.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by