Home > front end >  MATLAB string to integer conversion
MATLAB string to integer conversion

Time:07-06

I am a newbie at matlab. I have deployed a machine learning model(developed using python) using flask. From matlab, I have called the API and received a string response. The response is like: '[0.8]'. but matlab is showing the size of the string is 1. I need only the value 0.8. My code:

import matlab.net.http.*
import matlab.net.http.field.*

request = RequestMessage( 'POST', ...
    [ContentTypeField( 'application/vnd.api json' ), AcceptField('application/vnd.api json')], ...
    '{"meta": {"Speed_RPM_PU": 0.2}}' );
response = request.send( 'http://127.0.0.1:5000/predict' );
ans=response.Body.Data
length(ans) % equals to 1
% for i = 1:length(ans)
%  
%    fprintf('%c ',ans(i))
%  
%    %disp(String(i))
%  
% end

Here, ans='[0.8]'

CodePudding user response:

If ans='[0.8]' then length(ans) would be equal to 5 (because there are 5 characters in this char array). I suspect that you actually have ans={'[0.8]'}, i.e. a cell array of length 1 which contains a single char array. Otherwise you are using single quotation marks '_' which indicate a char where MATLAB is actually showing double quotation marks "_" which indicate a string, since the length would be 1 if it was a string too. Chars and strings are not equivalent.

Calling class(ans) instead of length(ans) would tell you which of these is correct.

You can use str2num(ans) in any case, but if it's a cell you'll need str2num(ans{1})

str2num('[0.8]') % = 0.8 (double from char)
str2num("[0.8]") % = 0.8 (double from string)

str2num({'0.8'}) % -> error
a = {'0.8'};
str2num(a{1})    % = 0.8 (double from char element of cell)

str2double is often preferred over str2num, but you would need to remove the square brackets from your char/string or it would give NaN, so something like

str2double( erase( '[0.8]', {'[',']'} ) ) % = 0.8 (double)

Note that ans is the default variable name for unassigned function outputs, consider using a different variable name to avoid unexpected issues.

  • Related