Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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

Respuesta aceptada

Cedric
Cedric el 4 de Jul. de 2014
Editada: Cedric el 4 de Jul. de 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 comentario
Cedric
Cedric el 4 de Jul. de 2014
Editada: Cedric el 4 de Jul. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by