【发布时间】:2017-10-13 19:40:51
【问题描述】:
我在 matlab 脚本中有一个名为“dataString”的字符串数组,它是使用 fileread() 从 html 文档复制到 MATLAB 中的。然后我剪下我想要的部分并将其存储在 dataString 中。
TEXT = fileread(htmldocument);
k1 = strfind(TEXT,stringDelimiter1)
k2 = strfind(TEXT,stringDelimiter2)
dataString(:) = TEXT(k1(1):(k1(1) - 1))
然后对其内容进行过滤,使其不包含 html 代码,但除了字母之外,它仍然可以包含特殊字符和数字。下面 dataString 内容的解决方案应该足以解决我要解决的问题的一般情况。 dataString 中包含各种字符和数字,并且在文本中具有特定点,在 MATLAB 中打印时可以看到回车符。如果我让 matlab 在命令行窗口中打印它,它会像这样格式化自己:
dataString =
'This is where the body of dataString goes.
There are not the same number of characters on
every line. Notice that MATLAB knows that there are
carriage returns interspersed throughout this text and
formats the output appropriately.
There are also numbers and other
types of characters in this array like 12, and %2
(m) %Z --- . When asked to print to the command window, MATLAB
treats all the contents of dataString as I want it to.
These contents need to be considered as generic as possible.
'
我希望能够使用 fopen、fprintf 和 fclose 来获取 dataString 的内容并将它们放入一个文本文件 'genericTextFileName.txt' 当我在 MATLAB 中打印 dataString 时在每一行打印出的字符也打印在文本文件的后续行上。当我执行以下操作时:
fileDirectory = 'C:\Users\UniqueWorldline\Desktop'
[fid, errorMsg] = fopen(fileDirectory, 'w')
byteCount = fprinf(fid, '%s', dataString)
fcloseFile = fclose(fid)
dataString 像这样打印到文本文件中:
dataString =
'This is where the body of dataString goes. There are not the same number of characters on every line. Notice that MATLAB knows that there are carriage returns interspersed throughout this text and formats the output appropriately. There are also numbers and other types of characters in this array like 12, and %2 (m) %Z --- . When asked to print to the command window, MATLAB treats all the contents of dataString as I want it to. These contents need to be considered as generic as possible.'
基本上,dataString 中存在的所有新行或回车格式都会丢失。删除 '%s' 并没有帮助,因为 fprintf 然后认为 '%' 是一个特殊字符,我不能让它这样做,因为它会删除第一个 '%' 之后的所有内容。我需要这种格式存在于文本文件中。在阅读了人们对 fprintf 和函数本身的文档的许多其他相关问题之后,我找不到我的问题的答案。我该怎么做?
【问题讨论】:
-
请参阅minimal reproducible example。
fprintf('%s', '12, %2 (m) %Z ---')按预期工作。 -
请再看一遍上面的链接。您错过了主题的完整和可验证部分。完全不清楚您实际上是如何定义
dataString。 -
1. MATLAB 中的字符串数组使用双引号
" "。你所拥有的是一个字符数组。 2. 正如 excaza 所说,尚不清楚您如何定义dataString -
我已经添加了更多关于 dataString 来自何处的信息,但它的确切来源无关紧要。重要的是它的数据类型、内容以及我想对这些内容做什么。我在问题中写的字符数组的解决方案足以解决我需要解决的一般情况。
-
@Sardar Usama,你是对的。我道歉。它是一个字符数组。但是,请参阅上面的评论。
标签: string matlab printf-debugging