matlab get the value of char

后端 未结 3 1985
面向向阳花
面向向阳花 2021-01-29 14:56

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

a =


            value_1
            value_2

and I wou

3条回答
  •  终归单人心
    2021-01-29 15:22

    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)];
    

提交回复
热议问题