如何将 'inputdlg' 输出转换为文本文件?
How to convert 'inputdlg' output into text file?
我正在编写一个显示字符数组的脚本(我会使用字符串数组,但 inputdlg 需要字符),允许用户编辑数组,并将新数组输出到文本文件中。
但是,我 运行 遇到无法将输出 (vals1) 格式化为文本文件的问题。我认为部分问题是 inputdlg 命令输出一个 1x1 数组,很难将其转换回我开始使用的逐行格式(在本例中为 arr)。
下面的代码输出一行,按列而不是按行读取:“A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m i t h”。我不确定如何转换它,因为 charvals1(inputdlg 输出)returns 是相同的字符串。
有没有办法在用户输入新数组后 return 逐行输出(而不是 1x1 数组字符串),或者打印 inputdlg 输出的重新格式化版本(包括换行符)?
arr = char(["ABCDE";
"123456789";
"Robert Smith";
"etc etc"])
% User updates the array
prompt = {'Update content below if necessary'};
dlgtitle = "Section 2";
dims = [30 50];
definput = {arr};
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = convertCharsToStrings(charvals1);
% Outputting the updated array to text file
prompt = {'Enter desired input file name'};
dlgtitle = "Input Name";
dims = [1 35];
definput = {'Input Name'};
fileName = inputdlg(prompt,dlgtitle,dims,definput);
selected_dir = uigetdir();
fileLocation = char(strcat(selected_dir, '\', string(fileName(1)),'.txt'));
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1) ;
不要使用 convertCharsToStrings,因为它会沿字符数组的第一维进行操作(您可以先转置字符数组,但随后 'linebreaks' 会丢失)。
您可以将获得的字符数组转换为字符串,然后 trim 空格。这可以写入文本文件,而您已有的代码没有任何问题。
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array.
vals1 = strtrim(vals1);
别忘了关闭 txtfile
:
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);
我正在编写一个显示字符数组的脚本(我会使用字符串数组,但 inputdlg 需要字符),允许用户编辑数组,并将新数组输出到文本文件中。
但是,我 运行 遇到无法将输出 (vals1) 格式化为文本文件的问题。我认为部分问题是 inputdlg 命令输出一个 1x1 数组,很难将其转换回我开始使用的逐行格式(在本例中为 arr)。
下面的代码输出一行,按列而不是按行读取:“A1ReB2otC3bcD4e E5re 6tt 7 c 8S 9m i t h”。我不确定如何转换它,因为 charvals1(inputdlg 输出)returns 是相同的字符串。
有没有办法在用户输入新数组后 return 逐行输出(而不是 1x1 数组字符串),或者打印 inputdlg 输出的重新格式化版本(包括换行符)?
arr = char(["ABCDE";
"123456789";
"Robert Smith";
"etc etc"])
% User updates the array
prompt = {'Update content below if necessary'};
dlgtitle = "Section 2";
dims = [30 50];
definput = {arr};
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = convertCharsToStrings(charvals1);
% Outputting the updated array to text file
prompt = {'Enter desired input file name'};
dlgtitle = "Input Name";
dims = [1 35];
definput = {'Input Name'};
fileName = inputdlg(prompt,dlgtitle,dims,definput);
selected_dir = uigetdir();
fileLocation = char(strcat(selected_dir, '\', string(fileName(1)),'.txt'));
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1) ;
不要使用 convertCharsToStrings,因为它会沿字符数组的第一维进行操作(您可以先转置字符数组,但随后 'linebreaks' 会丢失)。
您可以将获得的字符数组转换为字符串,然后 trim 空格。这可以写入文本文件,而您已有的代码没有任何问题。
charvals1 = inputdlg(prompt,dlgtitle,dims,definput);
vals1 = string(charvals1{1}); % note the {1} to access the contents of the cell array.
vals1 = strtrim(vals1);
别忘了关闭 txtfile
:
txtfile = fopen(fileLocation,'wt');
fprintf(txtfile, '%s\n', vals1);
fclose(txtfile);