フィルターのクリア

Create multiple copies of a .txt file according to N x 1 array

4 ビュー (過去 30 日間)
Matthew Worker
Matthew Worker 2023 年 9 月 19 日
コメント済み: Dyuman Joshi 2023 年 9 月 19 日
I have an N by 1 array that contains random integer values, say A = [101, 790, 477, ... , 999]. I also have a text file, say MyFile.txt, that contains rows of alphanumeric data. I wish to replace an integer value that appears on the 2nd row in MyFile.txt with an integer value from array A and then save this with a unique file name. I wish to repeat this for each element in the array A. This process should result in N text files as follows: MyFile_101.txt, MyFile_790.txt, MyFile_477.txt , ... , MyFile_999.txt.
Is there an efficient way to automate the above using a matlab script?
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 19 日
Can you attach the text file - 'MyFile.txt' ? Use the paperclip button to attach.
Matthew Worker
Matthew Worker 2023 年 9 月 19 日
Hi Dyuman, thanks for the reply. Please find attached. Note: it is the value 786 on line 2 that I wish to change each time.

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

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 9 月 19 日
編集済み: Dyuman Joshi 2023 年 9 月 19 日
The data in the text file is heterogeneous and stored non-uniformly. This approach should work for that -
y = readlines('MyFile.txt')
y = 19×1 string array
" 0" " 786" " 101" " 1" " 1" " 3" " 0" " H" " A" " J" " K" "h7lA" "K" "9" "11" "M" "AK" "PP" ""
%String to be replaced
str = strip(y(2))
str = "786"
%Let A be the array of values that need to be replace
A = [101, 790, 477, 999];
for k=1:numel(A)
z=y;
%Replacing the values
z(2) = regexprep(z(2),str,string(A(k)));
%Writing to a text file
%These files will be stored in the current directory
%You can change the path according to where you want to store them
writelines(z,sprintf('MyFile_%d.txt', A(k)));
end
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 19 日
You are welcome!
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 19 日
In that case, fprintf to the rescue -
y = readlines('MyFile.txt');
%String to be replaced
str = strip(y(2));
%Let A be the array of values that need to be replace
A = [101, 790, 477, 999];
for k=1:numel(A)
z=y;
%Replacing the values
z(2) = regexprep(z(2),str,string(A(k)));
%Creating file to store
fid = fopen(sprintf('MyFile_%d.txt', A(k)),'wt');
%Printing the data
fprintf(fid,'%s\n',z);
%Closing the file
fclose(fid);
end
%Checking the contents
type MyFile_790.txt
0 790 101 1 1 3 0 H A J K h7lA K 9 11 M AK PP

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by