how to convert from one class to another in matlab

2019-09-20 11:49发布

问题:

I have created a set of density values using the matlab function f=ksdensity(x) where x is a nx1 vector. Now this produces a result of class 'double'

{Columns 1 through 12

0.0001    0.0002    0.0003    0.0004    0.0006    0.0008    0.0012    0.0016    0.0022    0.0029    0.0038    0.0049

Columns 13 through 24

0.0062    0.0078    0.0095    0.0115    0.0136    0.0159    0.0183    0.0208    0.0233    0.0257    0.0281    0.0304

Columns 25 through 36

0.0327    0.0349    0.0370    0.0392    0.0414    0.0438    0.0463    0.0491    0.0521    0.0553    0.0586    0.0621

Columns 37 through 48

0.0656    0.0691    0.0723    0.0752    0.0776    0.0795    0.0808    0.0814    0.0814    0.0808    0.0796    0.0779

Columns 49 through 60

0.0758    0.0733    0.0707    0.0680    0.0652    0.0624    0.0597    0.0571    0.0547    0.0523    0.0501    0.0479

Columns 61 through 72

0.0459    0.0441    0.0423    0.0408    0.0393    0.0381    0.0370    0.0360    0.0352    0.0345    0.0338    0.0331

Columns 73 through 84

0.0324    0.0315    0.0305    0.0293    0.0279    0.0263    0.0244    0.0224    0.0203    0.0181    0.0158    0.0137

Columns 85 through 96

0.0116    0.0097    0.0079    0.0064    0.0051    0.0040    0.0030    0.0023    0.0017    0.0012    0.0009    0.0006

Columns 97 through 100

0.0004    0.0003    0.0002    0.0001}

But to further use this data I need to convert this into an array. How do I do that?

回答1:

The first output of ksdensity is already an array/vector.

In MATLAB, an array is not a class. It is a list of objects that each have the same class. Technically speaking, all MATLAB variables are arrays (any scalar is actually a 1 x 1 array).

So if we create an array:

x = [1.1, 1.2, 1.3];

The class is double

class(x)

    double

Or an array of integers

y = uint8([1,2,3]);

class(y)

    uint8

Or even if we get really crazy, we can have an array of structs

z = [struct(), struct(), struct()];

class(z)

    struct

So anything you want to do on your output (as an array) can already be done without any conversion.

Other datatypes (like cell arrays) may require some conversion to get then into a numeric array, but you're not dealing with that at this point. And you can always check their type with iscell or class(data) == 'cell'



标签: matlab class