Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
H-H
H-H le 4 Juil 2014
Modifié(e) : Cedric le 4 Juil 2014
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

Réponse acceptée

Cedric
Cedric le 4 Juil 2014
Modifié(e) : Cedric le 4 Juil 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 commentaire
Cedric
Cedric le 4 Juil 2014
Modifié(e) : Cedric le 4 Juil 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by