如何在MATLAB中连接存储在变量中的字符串和数字

时间:2013-12-20 00:14:05

标签: string matlab concatenation

我正在尝试从XML读取标记,然后想要将数字连接到它。 首先,我将字符串的值保存到变量并尝试连接它 使用for循环中的变量。但它会引发错误。

for i = 0:tag.getLength-1
                node = tag.item(i);
                disp([node.getTextContent]);

                str=node.getTextContent;

                str= strcat(str, num2str(i))
                new_loads = cat(2,loads,[node.getTextContent]);                
            end

引发的错误是

Operands to the || and && operators must be
convertible to logical scalar values.

Error in strcat (line 83)
if ~isempty(str) && (str(end) == 0 ||
isspace(str(end)))

Error in SMERCGUI>pushbutton1_Callback (line 182)
                str= strcat(str,' morning')

Error in gui_mainfcn (line 96)
    feval(varargin{:});

Error in SMERCGUI (line 44)
gui_mainfcn(gui_State, varargin{:});

Error in
@(hObject,eventdata)SMERCGUI('pushbutton1_Callback',hObject,eventdata,guidata(hObject))


Error while evaluating uicontrol Callback

1 个答案:

答案 0 :(得分:1)

错误表明您的字符串不是字符串。我不清楚它是在strcat行还是在cat行以后抛出错误。

无论如何,应该很清楚,你不能将不同类型的元素连接成一个数组 - 单元格数组是,常规数组否。这一行

new_loads = cat(2,loads,[node.getTextContent]); 

肯定会出问题。 2是数字,node.getTextContent是字符串 - 或者可能是单元格数组或其他内容。我看不出loads是什么,所以我不知道这是否与问题有关。

通常将数字和字符串组合成单个字符串的好方法是

newString = sprintf('%s %d', oldString, number);

然后,您可以使用printf的所有格式化技巧来完全按照您的意愿生成输出。但在您执行任何操作之前,请确保您了解要尝试串联的所有元素的类型。对内存中的所有元素执行此操作的最简单方法是

whos

或者如果您只想要一个变量,

whos str

或所有以s:

开头的变量
whos s*

输出不言自明。如果你在此之后仍然无法弄明白,请发表评论,我会尽力帮助你。

编辑根据我在http://blogs.mathworks.com/community/2010/11/01/xml-and-matlab-navigating-a-tree/上阅读的内容,您可能只需将str变量转换为Matlab字符串(显然它是一个java.lang) 。串)。所以尝试添加

str = char(str);

在使用str之前。这可能就是你所需要的。

相关问题