필터 지우기
필터 지우기

How to generate sequences from two vectors using rowfun

조회 수: 1 (최근 30일)
Etsuko
Etsuko 2016년 7월 13일
편집: Stephen23 2016년 7월 13일
Hi,
I am trying to generate sequences for which starting values and last values+1 are contained in vectors, without using for-loop. Because there is a lot of data to process, doing for-loop is unfortunately not feasible. As the output, I want to have all the sequences to be concatenated into one vector. I think rowfun can help me here, but so far I have not been successful. If someone can give me a helping hand, I would be grateful.
This is an example;
x = [1,6,12]'; y = [5,10,13]';
the output I wish to obtain: z = [1,2,3,4,6,7,8,9,12];
I imagine it should be something like;
inputvecs = table(x,y);
z = rowfun(@seqgen,inputvecs)
How should the function seqgen look in this case? Should concatenation within the function?
Thank you very much for your help.
Etsuko

채택된 답변

Stephen23
Stephen23 2016년 7월 13일
편집: Stephen23 2016년 7월 13일
You could use arrayfun instead:
>> x = [1,6,12]; y = [5,10,13];
>> cell2mat(arrayfun(@(a,b)a:b-1, x,y,'UniformOutput',false))
ans =
1 2 3 4 6 7 8 9 12
or
>> tmp = arrayfun(@(a,b)a:b-1,x,y,'UniformOutput',false);
>> horzcat(tmp{:})
ans =
1 2 3 4 6 7 8 9 12
Note that the inputs must be horizontal vectors.
  댓글 수: 2
Etsuko
Etsuko 2016년 7월 13일
편집: Etsuko 2016년 7월 13일
Thank you so much for your help, Stephen and Andrei!
Here I compared time for these three methods;
>> x = [1,6,12]; y = [5,10,13];
>> tic; cell2mat(arrayfun(@(a,b)a:b-1, x,y,'UniformOutput',false)); toc
Elapsed time is 0.008368 seconds.
>> tic; tmp = arrayfun(@(a,b)a:b-1,x,y,'UniformOutput',false);horzcat(tmp{:}); toc
Elapsed time is 0.000757 seconds.
>> tic; a = (min(x):max(y))';[ii,~] = find(bsxfun(@ge,a,x)&bsxfun(@lt,a,y));out = a(ii);toc
Elapsed time is 0.003983 seconds.
Thank you!
Stephen23
Stephen23 2016년 7월 13일
편집: Stephen23 2016년 7월 13일
@Etsuko: note that to get meaningful timing values for such quick functions, it is recommended to repeat the process a few hundred or thousand times.

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2016년 7월 13일
편집: Andrei Bobrov 2016년 7월 13일
x = [1,6,12]; y = [5,10,13];
a = (min(x):max(y))';
[ii,~] = find(bsxfun(@ge,a,x)&bsxfun(@lt,a,y));
out = a(ii);

카테고리

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