Parsing a vector
Afficher commentaires plus anciens
Hi,
Given a vectors say a = [1 3 5 NaN 4 5 NaN 8 9] I would like to create new vectors of the following form b = [1 3 5]; c = [4 5]; d = [8 9];
Thanks for your help,
-n
Réponse acceptée
Plus de réponses (2)
Paulo Silva
le 3 Août 2011
a = [1 3 5 NaN 4 5 NaN 8 9]
b=[0 find(isnan(a)) numel(a)+1]
c=arrayfun(@(x)a(b(x)+1:b(x+1)-1),1:numel(b)-1,'uni',0)
c(cellfun(@isempty,c))=[]; %remove empty cells caused by consecutive NaN
c{:}
I did this simple benchmark just for fun in MATLAB 2008b

%each loop the NaN are put in a like this
s=10000; %the step of the loop, first value is also equal to s
a=randi([1 100],1,n); %values of the vector a, random integer from 1 to 100
per=randperm(n); %permute the indexes
nnan=randi([1 s]); %get random number of nans
a(per(1:nnan))=NaN; %set the first nnan indexes of a equal to nan
Behaviour of each code varying the number of NaN and keeping the vector with fixed size.

By mistake I had my line of code that removes empty cells commented, it's a little faster but the results might have empty cells that resulted from consecutive NaN values.
%each loop the number of NaN increases by 100 until 10000,
%locations of the NaN values per loop are randomized with this code
s=10000; %this is the number of columns of vector a
a=randi([1 100],1,s); %the vector a full of integers from 1 to 100
per=randperm(s); %generate the permutation of index values
a(per(1:nn))=NaN; %put NaN on the first nn permuted index values
Same thing but now with my full code, little bit slower.

Another test, now like Fangjun suggested I used cellfun('isempty') instead of cellfun(@isempty) on my code, it does look faster now.

4 commentaires
Jan
le 3 Août 2011
+1: I like embedded graphics.
Fangjun Jiang
le 3 Août 2011
Interesting! Nice work, Paulo!
My guess is that regexp() or string processing is relatively slow.
Jan told me that cellfun('isempty') is much faster than cellfun(@isempty). Wonder whether that will make a difference in your code.
Paulo Silva
le 3 Août 2011
Fangjun that part of my code doesn't take much time, actually with or without it doesn't seem to change the execution time, I also tested your suggestion, can't notice much difference.
Paulo Silva
le 3 Août 2011
ok Fangjun I did more tests and it really is faster with cellfun('isempty') :)
Fangjun Jiang
le 3 Août 2011
I couldn't resist trying a solution without for-loop. It considered consecutive NaNs.
a = [1 3 5 NaN NaN 4.4 5 NaN 8 9];
b=num2str(a);
c=regexp(b,'(NaN\s+)+','split');
d=cellfun(@str2num,c,'uni',0)
d{1}
d{2}
d{3}
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!