필터 지우기
필터 지우기

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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by