필터 지우기
필터 지우기

Parsing a vector

조회 수: 3 (최근 30일)
Nora
Nora 2011년 8월 2일
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

채택된 답변

Jan
Jan 2011년 8월 2일
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

추가 답변 (2개)

Paulo Silva
Paulo Silva 2011년 8월 3일
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
Paulo Silva
Paulo Silva 2011년 8월 3일
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 2011년 8월 3일
ok Fangjun I did more tests and it really is faster with cellfun('isempty') :)

댓글을 달려면 로그인하십시오.


Fangjun Jiang
Fangjun Jiang 2011년 8월 3일
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}

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by