Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab string vector / array handling (multiplication u and str2num)

I would like to understand if this is really correct, or if this might be an issue in matlab.

I create an string vector/array via:

>>a=['1','2';'3','4']

It returns:

 a =
    12
    34

Now I would like to convert the content from string to number and multiply this with a number:

>>6*str2num(a)

The result looks like this:

 a =
    72
    204

I don't understand why the comma separated elements (strings) will be concatenated and not separated handled. If you use number instead of strings they will be separated handled. Then it looks like this:

>> a=[1,2;3,4]

a =
     1     2
     3     4

>> 6*a

ans =
     6    12
    18    24

I would expect the same results. Any ideas ?

Thanks

like image 555
ignoramus Avatar asked Jul 11 '26 10:07

ignoramus


1 Answers

Have you read about how string handling is done in MATLAB?

Basically, multiple strings can only be stored as a column vector (of strings). If attempted to store as a row vector, they will be concatenated. This is why strings '1' and '2' are being concatenated, as well as '3' and '4'. Also note, that this is only possible if all resulting strings are of the same length.

I'm not sure what you're trying to do, but if you want to store strings as a matrix (that is, multiple strings in a row), consider storing them in a cell array, for instance:

>> A = {'1', '2'; '3', '4'}

A = 
    '1'    '2'
    '3'    '4'

>> cellfun(@str2num, A)

ans =
    1     2
    3     4
like image 153
Eitan T Avatar answered Jul 14 '26 01:07

Eitan T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!