Parsing a vector
8 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 2 Aug 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
0 Comments
More Answers (2)
Paulo Silva
on 3 Aug 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 Comments
Paulo Silva
on 3 Aug 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
on 3 Aug 2011
ok Fangjun I did more tests and it really is faster with cellfun('isempty') :)
Fangjun Jiang
on 3 Aug 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}
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!