Parsing a vector

8 vues (au cours des 30 derniers jours)
Nora
Nora le 2 Août 2011
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

Jan
Jan le 2 Août 2011
It would not be a good idea to create 'b', 'c', 'd', ... automatically. Better create a cell array:
a = [1 3 5 NaN 4 5 NaN 8 9];
a = [NaN, a, NaN];
sepInd = find(isnan(a));
nSep = length(sepInd) - 1;
b = cell(1, nSep);
for i = 1:nSep
b{i} = a(sepInd(i) + 1:sepInd(i + 1) - 1);
end

Plus de réponses (2)

Paulo Silva
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
Paulo Silva
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
Paulo Silva le 3 Août 2011
ok Fangjun I did more tests and it really is faster with cellfun('isempty') :)

Connectez-vous pour commenter.


Fangjun Jiang
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 Logical dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by