How to index two vectors together
3 views (last 30 days)
Show older comments
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 Comments
Stephen23
on 24 Nov 2023
"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{:}]
Dyuman Joshi
on 24 Nov 2023
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
tic
C = arrayfun(@colon,vec_A,vec_B,'uni',0);
toc
Accepted Answer
Dyuman Joshi
on 24 Nov 2023
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
out1 = [out1{:}]
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
out2 = [out2{:}]
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.
0 Comments
More Answers (1)
Bruno Luong
on 24 Nov 2023
Edited: Bruno Luong
on 24 Nov 2023
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
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!