MAV
MAV

Reputation: 92

How do I concatenate a string stored in variable and a number in MATLAB

I am trying to read a tag from XML and then want to concatenate a number to it. Firstly, I am saving the value of the string to a variable and trying to concatenate it with the variable in the for loop. But it throws an error.

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

Error thrown is

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

Upvotes: 0

Views: 545

Answers (1)

Floris
Floris

Reputation: 46435

The error suggests that your string is not a string. It's not clear to me whether it's throwing an error at the strcat line, or at the later cat line.

At any rate, it should be clear that you cannot concatenate elements of different types into an array - cell array yes, regular array no. So the line

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

is bound to give a problem. 2 is numerical, and node.getTextContent is a string - or maybe a cell array or something else. I can't see what loads is, so I can't tell if that is involved in the problem.

Usually a good way to combine numbers and strings into a single string is

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

You can then use all the formatting tricks of printf to produce output exactly as you want. But before you do anything, make sure you understand the type of all the elements you are trying to string together. The easiest way to do this for all the elements in memory is

whos

Or if you just want it for one variable,

whos str

Or all variables starting with s:

whos s*

The output is self-explanatory. If you still can't figure it out after this, leave a comment and I'll try to help you out.

EDIT based on what I read at http://blogs.mathworks.com/community/2010/11/01/xml-and-matlab-navigating-a-tree/ , it is possible that you just need to cast your str variable to a Matlab string (apparently it's a java.lang.string). So try to add

str = char(str);

before using str. It may be what you need.

Upvotes: 1

Related Questions