How to index two vectors together

3 次查看(过去 30 天)
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