Replacing an array with string using condition

3 visualizzazioni (ultimi 30 giorni)
Sowmya MR
Sowmya MR il 20 Ott 2016
Modificato: Walter Roberson il 21 Ott 2016
Hi,
I have an array X=[0 0.1 0.2 0.3..... 30]. Now i should replace all values between a range with a string. For example: X(X>=0 &X<4)='delta', X(X>=4 &X<8)='theta', X(X>=8 &X<12)='alpha', X(X>=12 &X<30)='beta'. Can someone please help me with this?

Risposte (1)

Walter Roberson
Walter Roberson il 20 Ott 2016
That cannot be done in MATLAB. In MATLAB, numeric arrays cannot hold strings.
You could convert the numeric array to a cell array and store strings in that.
X_cell = num2cell(X);
I suggest you learn how to use logical indexing:
mask = X>=4 & X<8;
X_cell(mask) = {'something'};
  2 Commenti
Sowmya MR
Sowmya MR il 20 Ott 2016
Thank you. I tried this but get an error "Conversion to cell from char is not possible. "
Walter Roberson
Walter Roberson il 21 Ott 2016
Modificato: Walter Roberson il 21 Ott 2016
>> X = (rand(3,5)*10);
>> X_cell = num2cell(X);
>> mask = X>=4 & X<8;
>> X_cell(mask) = {'something'};
>> X_cell
X_cell =
3×5 cell array
'something' [0.461713906311539] 'something' [0.344460805029088] 'something'
[0.318328463774207] [0.971317812358475] [3.17099480060861] 'something' 'something'
[ 2.7692298496089] [ 8.23457828327293] [9.50222048838355] [ 3.81558457093008] [1.86872604554379]

Accedi per commentare.

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by