Use of cellfun to obtain the 2 element ONLY

2 ビュー (過去 30 日間)
Natalia Lopez
Natalia Lopez 2019 年 8 月 28 日
コメント済み: Bruno Luong 2019 年 8 月 28 日
Hi!
So I have a dataset with all the elements/answers being: 'A1 A2 A3 A4'. I need to transform those elements into '1, 2, 3,4'. Basically I just need to get rid of the 'A'. I have been trying this > Mydata=cellfun(@(x)x(2),Mydata); Im trying to extract the second element only (1,2,3,4) for the whole dataset but I get the followign error:
Index exceeds the number of array elements (0).
Error in @(x)x(2)
The format is 'cell' (not table). I then need to apply a fuction to substract 1 to each element, so 1=0, 2=1, 3=2 and 4=3. If anyone could help me i would really appreciate it! I'm obviously very new to matlab.
Many thanks!
  2 件のコメント
Walter Roberson
Walter Roberson 2019 年 8 月 28 日
At least one of the elements of Mydata is an empty cell.
Natalia Lopez
Natalia Lopez 2019 年 8 月 28 日
Thank you for your answer, yes I do have some missing data points. is there a way I can go around this? maybe just substituing the missing points for Nan or '.'?

サインインしてコメントする。

回答 (2 件)

Bruno Luong
Bruno Luong 2019 年 8 月 28 日
編集済み: Bruno Luong 2019 年 8 月 28 日
>> c={'A1' 'A2' 'A3' 'A4' ''}
c =
1×5 cell array
{'A1'} {'A2'} {'A3'} {'A4'} {0×0 char}
This throw an error
Mydata=cellfun(@(x)x(2),c)
Index exceeds the number of array elements (0).
Error in @(x)x(2)
This works but returns -16 for empty cell.
a=char(c);
num=a(:,2)-'0'
num =
1
2
3
4
-16
You can replace with NaN
num(num<0)=NaN
num =
1
2
3
4
NaN
  2 件のコメント
Natalia Lopez
Natalia Lopez 2019 年 8 月 28 日
Thanks for your answer, I did try it and it now I got the error:
Index in position 2 exceeds array bounds (must not exceed 1).
%Importfile(Mydata)
load(Mydata.mat');
Mydata = xData(:,i); %coded as A1, A2, A3, A4, -> change to 1 2 3 4
Mydata = table2array(data2); % convert to cell array
ids= cellfun(@(x) x(2),data2); % to each cell, apply the inline function that takes the second element
Bruno Luong
Bruno Luong 2019 年 8 月 28 日
Try my second method

サインインしてコメントする。


Walter Roberson
Walter Roberson 2019 年 8 月 28 日
cellfun(@(S) sscanf(S,'%*c%d'), c, 'uniform', 0)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by