matlab get the value of char

2020-05-10 08:34发布

from MATLAB command line , when I type my variable a , it gives me values as expected :

a =


            value_1
            value_2

and I would like to access to each value of a, I tried a(1) but this gives me empty the type of a is 1x49char. how could I get value_1 and value_2 ?

 whos('a')
  Name      Size            Bytes  Class    Attributes

  a         1x49               98  char 

I get the a from xml file :

<flag ="value">
    <flow>toto</flow>
     <flow>titi</flow>
 </flag>

a+0:

ans =    
    10  32  32   32  32  32  32  32  32  32  32  32  32  98,...
   111 111 108  101  97 110  95  84  10  32  32  32  32  32,...
   32   32  32   32  32  32  32  66  79  79  76  10  32  32,...
   32   32  32   32  32  32  32

3条回答
叛逆
2楼-- · 2020-05-10 09:12

You seem to have an somewhat inconvenient character array. You can convert this array in a more manageable form by doing something like what @Richante said:

strings = strread(a, '%s', 'delimiter', sprintf('\n'));

Then you can reference to toto and titi by

>> b = strings{2}
b = 
toto

>> c = strings{3}
c = 
titi

Note that strings{1} is empty, since a starts with a newline character. Note also that you don't need a strtrim -- that is taken care of by strread already. You can circumvent the initial newlines by doing

strings = strread(a(2:end), '%s', 'delimiter', sprintf('\n'));

but I'd only do that if the first newline is consistently there for all cases. I'd much rather do

strings = strread(a, '%s', 'delimiter', sprintf('\n'));
strings = strings(~cellfun('isempty', strings))

Finally, if you'd rather use textscan instead of strread, you need to do 1 extra step:

strings = textscan(a, '%s', 'delimiter', sprintf('\n'));
strings = [strings{1}(2:end)];
查看更多
Bombasti
3楼-- · 2020-05-10 09:16

Perhaps a is a string with a newline in it. To make two separate variables, try:

values = strtrim(strread(a, '%s', 'delimiter', sprintf('\n')))

strread will split a into separate lines, and strtrim will remove leading/trailing whitespace. Then you can access the lines using

values{1}
values{2}

(note that you must use curly brackets since this is a cell array of strings).

查看更多
Deceive 欺骗
4楼-- · 2020-05-10 09:29

How are you reading in the xml file? If you're using xmlread then MatLab adds a lot of white space in there for you and could be the cause of your problems.

http://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct

This will put your xml file into a struct where you should be able to access the elements in the array.

查看更多
登录 后发表回答