How to index two vectors together

조회 수: 3 (최근 30일)
Guillem
Guillem 2023년 11월 24일
편집: Bruno Luong 2023년 11월 24일
Hi!
I'd like to know how i can index two vectors together. By that I mean that, if for example I have the following two vectors:
vec_A = [1 11 21 31];
vec_B = [4 14 24 34];
How can I get the following vector
vec_C = [1:4 11:14 21:24 31:34];
I know I can do it with a for loop, but is there a way just to do it with vectors?
Thank you very much in advance,
Guillem
  댓글 수: 2
Stephen23
Stephen23 2023년 11월 24일
"is there a way just to do it with vectors?"
Not really in a general way. But you can certainly hide the loop:
A = [1,11,21,31];
B = [4,14,24,34];
C = arrayfun(@colon,A,B,'uni',0);
C = [C{:}]
C = 1×16
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
Dyuman Joshi
Dyuman Joshi 2023년 11월 24일
I sometimes forget that such functions exist. Using colon seems to be faster.
But, as I mentioned earlier, for loop would be the best method here.
%Bigger data
vec_A = 10.*(1:1e5)+1;
vec_B = vec_A+3;
tic
out1 = arrayfun(@(x, y) x:y, vec_A, vec_B, 'uni', 0);
toc
Elapsed time is 0.212617 seconds.
tic
C = arrayfun(@colon,vec_A,vec_B,'uni',0);
toc
Elapsed time is 0.076981 seconds.

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

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 11월 24일
One way is to use arrayfun() but that is just a for loop in disguise.
%Bigger data
vec_A = 10.*(1:1e5)+1;
vec_B = vec_A+3;
tic
out1 = arrayfun(@(x, y) x:y, vec_A, vec_B, 'uni', 0);
toc
Elapsed time is 0.214490 seconds.
out1 = [out1{:}]
out1 = 1×400000
11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 51 52 53 54 61 62 63 64 71 72 73 74 81 82
This is same as -
n = numel(vec_A);
out2 = cell(1,n);
tic
for k=1:n
out2{k} = vec_A(k):vec_B(k);
end
toc
Elapsed time is 0.037649 seconds.
out2 = [out2{:}]
out2 = 1×400000
11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 51 52 53 54 61 62 63 64 71 72 73 74 81 82
However, you can see that the for loop is approximately 5.5 times faster than the arrayfun. So, performance wise for loop is the best option.

추가 답변 (1개)

Bruno Luong
Bruno Luong 2023년 11월 24일
편집: Bruno Luong 2023년 11월 24일
There is FEX, and fast if you have compiler and compile the mex file.
>> A = [1,11,21,31];
>> B = [4,14,24,34];
>> mcolon(A,B)
ans =
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
>> A:B
ans =
1 2 3 4
You can also overload MATLAB colon operator
>> mcolonops on
>> A:B
ans =
1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34
>> mcolonops off
>> A:B
ans =
1 2 3 4

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by